在 Typescript 中,如何将泛型传递给索引访问类型?

C. *_*ser 7 javascript typescript reactjs redux

我正在对 redux 存储进行一些重构,我想创建一个可用于减少重复代码的“工厂”类型。

目前,我将其设置为:

interface CommonFactory<T, S> {
  Payload: Partial<S>;
  Action: Action<T> & { payload: this['Payload'] };
  ActionCreator: ActionCreator<this['Payload']>;
}
Run Code Online (Sandbox Code Playgroud)

这使我可以通过简单地编写来提取一堆常见类型

interface AppState {
  key1: any;
  key2: any;
  key3: any;
}

type Factory = CommonFactory<AppTypes, AppState>;

type AppPayload = Factory['Payload'];
type AppAction = Factory['Action'];
type AppActionCreator = Factory['ActionCreator'];
Run Code Online (Sandbox Code Playgroud)

但是,我意识到有效负载的 Partial 是不正确的。我宁愿使用 Pick,以便 ActionCreator 可以指定要返回的属性。这不需要由Factory传递,而是由ActionCreator传递。就像是

const someActionCreator: AppActionCreator<'key1'> = (someData: any) => {
  return {
    type: SOME_ACTION_TYPE,
    payload: {
      key1: someData
    }
  }
}
Run Code Online (Sandbox Code Playgroud)

但我不确定如何将泛型传递给索引访问类型。