【问题标题】:Explanation of action creator and extraction of types from them动作创建者的解释和从中提取类型
【发布时间】: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&lt;...&gt; 的原因是因为它会抱怨缺少create 属性,该属性存在于类中,而不是create 方法返回的内容。

export type Action = Partial<typeof ActionCreators[keyof typeof ActionCreators]>;

我想知道的是以下内容;有人可以解释一下typeof ...[keyof typeof ...] 的工作原理,如果可能的话;对此提供替代解决方案,以解决缺少的 create 属性 - 一种仅包含来自 create 方法的可能返回的类型。

谢谢。

【问题讨论】:

    标签: reactjs typescript redux react-redux


    【解决方案1】:

    tl;drtypeof SomeObject[keyof typeof SomeObject] 的结果类型将是 SomeObject 的值类型中的 the union。在您的示例中Partial&lt;ActionCreator&lt;"TestAction", string&gt;&gt;。它基本上是所有现有操作的列表。


    下面是对步骤的解释:

    1. typeof ActionCreators: 告诉 TS 使用 const 的类型
    2. keyof (1):会给你联合类型ActionCreators的所有键。在您的情况下,它只有一个:TestAction
    3. typeof ActionCreators[(2)] 将为您提供所有键的值。它或多或少是在“迭代”对象并“返回”其值类型。

    您使用哪个版本的 TypeScript?当我删除 Partial(使用 TS 2.6.2)时,我没有收到错误。

    【讨论】:

    • 首先,非常感谢您的解释!我正在使用 2.7.1。当我尝试创建像 const testAction: Action = { type: 'TestAction', payload: 'random string' }; 这样的操作时,出现了问题。我现在在手机上,但我可以在回家后更新更多信息。
    • 好吧,我现在有一个测试,它导入动作,并尝试创建一个动作如下:const action: Action = ActionCreators.TestAction.create('test value'); Typescript 然后给出这个错误:Type '{ type: "TestAction"; payload: string; }' is not assignable to type 'ActionCreator&lt;"TestAction", string&gt;'. Property 'create' is missing in type '{ type: "TestAction"; payload: string; }'.
    • 这有点难读。您可以创建一个codesandbox 或用于测试目的的东西吗?
    • 当然; codesandbox.io/s/7zqzrjjv3x。讨论的代码来自存储库github.com/FredrikAugust/typescript-react-boilerplate,讨论的文件是test/defaultReducer.test.tssrc/actions/action-creator.tssrc/reducers/reducer.ts
    • 我不确定这是不是上面代码的问题,因为代码和框没有显示任何错误(将鼠标悬停在 create 实际上也显示了正确的类型)。我在我的编辑器中复制/粘贴了代码,那里一切正常。类型推断也有效。我创建了另一个只接受number 而不是string 的动作,并且打字稿成功地警告了我。
    猜你喜欢
    • 1970-01-01
    • 2018-11-22
    • 2021-02-01
    • 2021-09-13
    • 2014-12-24
    • 1970-01-01
    • 1970-01-01
    • 2019-11-15
    • 2021-09-29
    相关资源
    最近更新 更多