【发布时间】:2018-02-06 22:50:35
【问题描述】:
我正在使用 typescript、react 和 redux 组合一个小应用程序,我遇到了一个叫做动作创建器的小东西。
action creator类的代码如下,原创者,props到github@plotrwitek;
export class ActionCreator<T, P> {
readonly type: T;
readonly payload: P;
constructor(type: T) {
this.type = type;
}
create = (payload: P) => ({
type: this.type,
payload
});
}
现在,在 reducer 中,我正在实例化这些动作创建者,并提取不同的类型,如下所示;
export const ActionCreators = {
TestAction: new ActionCreator<'TestAction', string>('TestAction'),
};
我在下面使用Partial<...> 的原因是因为它会抱怨缺少create 属性,该属性存在于类中,而不是create 方法返回的内容。
export type Action = Partial<typeof ActionCreators[keyof typeof ActionCreators]>;
我想知道的是以下内容;有人可以解释一下typeof ...[keyof typeof ...] 的工作原理,如果可能的话;对此提供替代解决方案,以解决缺少的 create 属性 - 一种仅包含来自 create 方法的可能返回的类型。
谢谢。
【问题讨论】:
标签: reactjs typescript redux react-redux