首页 > 解决方案 > 根据值向界面添加键?

问题描述

设想

我的场景是我有两个类,第一个是粗略的 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,还是目前不可能?

标签: typescript

解决方案


一种方法是

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[]>([]) });

推荐阅读