场景
我在这里的场景是我有两个类,第一个是一个粗略的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上,或者这目前还不可能吗?
发布于 2021-01-05 21:32:07
一种方法是
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[]>([]) });https://stackoverflow.com/questions/65575228
复制相似问题