这就是我使用 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 以支持命名空间更改?
答案 0 :(得分: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"]
>;