【问题标题】:declare type in TypeScript based on the return type of a generator function根据生成器函数的返回类型在 TypeScript 中声明类型
【发布时间】:2021-02-11 07:14:25
【问题描述】:

这就是我使用 ActionCreater 及其类型定义动作的方式。

   const listRequestAction = new ActionCreator<undefined, undefined>(
        REQUEST_LIST
      );
    
   type listRequestActionType = ReturnType<
        typeof listRequestAction.create
        >;

我想为我的操作添加一个动态命名空间,所以我对操作进行了此更改。

       const listRequestAction = (namespace: string) => 
          new ActionCreator<undefined, undefined>(
            `${namespace}${REQUEST_LIST}`
          );

如何重新定义 listRequestActionType 以支持命名空间更改?

【问题讨论】:

  • 请分享可重现的例子

标签: typescript react-redux typescript-typings


【解决方案1】:

这仅适用于 TS 4.2 及更高版本。 (https://github.com/Microsoft/TypeScript/wiki/Roadmap)

Playground link。不过,似乎有点冗长。随意重构它。

// Is this the correct reference? https://github.com/cameronmaske/react-redux-typescript
class ActionCreator<T, P> {
    readonly type: T;

    constructor(type: T) { this.type = type; }
    create = (payload: P) => ({ type: this.type, payload });
}


// I assume `REQUEST_LIST` is a string constant?
const REQUEST_LIST: "REQUEST_LIST" = "REQUEST_LIST"


const listRequestAction = <P, Namespace extends string>(
    namespace: Namespace
    ): ActionCreator<`${Namespace}${typeof REQUEST_LIST}`, P> =>
        new ActionCreator(
            `${namespace}${REQUEST_LIST}` as `${Namespace}${typeof REQUEST_LIST}`
        )

type listRequestActionType<P, Namespace extends string> = ReturnType<
    ActionCreator<`${Namespace}${typeof REQUEST_LIST}`, P>["create"]
>;

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-09-26
    • 1970-01-01
    • 1970-01-01
    • 2019-04-09
    • 2020-05-28
    • 1970-01-01
    • 2021-05-26
    • 1970-01-01
    相关资源
    最近更新 更多