在TypeScript中根据生成器函数的返回类型声明type



这就是我如何使用ActionCreater和它的Type来定义一个动作。

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来支持命名空间的变化?

这只能在TS 4.2及更高版本中实现。(https://github.com/Microsoft/TypeScript/wiki/Roadmap)

操场上链接。不过看起来有点啰嗦。请随意重构它。

// 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"]
>;

最新更新