typescript - 根据值向界面添加键?
问题描述
设想
我的场景是我有两个类,第一个是粗略的 ObservableStore 类,另一个基类可以传递一些 ObservableStore-s 值。
class ObservableStore<T> {
update(value: (current: T) => T): void;
subscribe(fn: (current: T) => void): void;
}
class OtherClass<Props extends {} = {}> {
constructor(private props: Props) {
for(let [key, value] of Object.entries(props)) {
if(value instanceof ObservableStore) value.subscribe($data => this[`$${key}`] = $data);
}
}
}
const someInstance = new OtherClass({ someStore: new ObservableStore<string[]>([]) });
问题
无论如何使用类型将$someStore
值添加到this.props
,还是目前不可能?
解决方案
一种方法是
class ObservableStore<T> {
constructor(arg: T[]) {
// ...
}
update(value: (current: T) => T): void { }
subscribe(fn: (current: T) => void): void { }
}
type Props<T> = Record<string, ObservableStore<T>>;
class OtherClass<T> {
constructor(private props: Props<T> = {}) {
for (let [key, value] of Object.entries(props)) {
// has to cast `this` for dynamic properties here, perhaps there is another workaround
if (value instanceof ObservableStore) value.subscribe($data => (this as unknown as Record<string, T>)[key] = $data);
}
}
}
const someInstance = new OtherClass<string[]>({ someStore: new ObservableStore<string[]>([]) });
推荐阅读
- php - Laravel6 - 具有相同名称的多个表单输入
- python - Python中的算法,用于在训练、验证和测试中进行最佳拆分
- excel - VBA Range.Find 识别所有单词“日期”并存储其位置
- python - 调试 CPython 内存碎片
- excel - Excel** 不同工作表中日期之间的小时时差
- react-native - 无法在 ReactNative 应用程序的 ListItem 中更改 Switch 的值
- matlab - 尝试运行使用 PSEXEC 打开 MATLAB 的批处理文件
- ios - 使用 .xib 启动屏幕更新旧 iOS 应用程序以满足 AppStore 的新故事板要求的最简单方法是什么?
- gd - 已安装 php-gd 但在 centos 7(php 7.3 版本)中无法运行
- typescript - 我可以从函数的返回类型推断元组类型,而不使用'as const'吗?