如何在泛型内部使用reduce?

时间:2019-05-15 07:16:09

标签: reactjs typescript mobx

上下文正在将Mobx与React结合使用,试图编写一个类,该类接收具有存储的对象并创建共享引用。

    class RootStore<T, K extends keyof T> {
      constructor(stores: T) {
        const storesWithRef: T = Object.keys(stores).reduce((acc: T, key: K) => {
            const store = stores[key];
            return ({
              ...acc,
              [key]: store.connectStore(this),
            });
          }, {});
        Object.assign(this, storesWithRef);
      }

这是每个商店基地的接口-

    export interface BaseStoreInterface<T> {
      rootStore: T;
      connectStore: (rootStore?: T) => T;
      externalStore: boolean;
    }

这段代码可以正常工作,但是TypeScript给了我两个错误-
 enter image description here

String is not assignable to type 'K'

并且- enter image description here

我知道需要做什么,但是我无法使其工作。 我正在使用TypeScript@3.4.5

代码很好,没有错误,没什么,在这些错误上添加ts-ignore可以保证良好的运行时间。

有什么想法吗?

0 个答案:

没有答案