【发布时间】:2022-01-21 12:08:54
【问题描述】:
我正在尝试使用模板文字类型来创建 Redux 操作的类型化组,例如“FETCH/START”、“FETCH/PENDING”等。
我想使用@reduxjs/toolkit createAction 来制作我的动作创建者,如下所示:
import { createAction, ActionCreatorWithoutPayload, ActionCreatorWithOptionalPayload } from "@reduxjs/toolkit";
interface IFluxAction<T extends string, P> {
Started: ActionCreatorWithOptionalPayload<P, `${T}/START`>;
Pending: ActionCreatorWithoutPayload<`${T}/PENDING`>;
}
const createAsyncActions = <P>() => <T extends string>(type: T):
IFluxAction<T, P> => {
return {
// Type 'undefined' is not assignable to type 'P'.
// 'P' could be instantiated with an arbitrary type which
// could be unrelated to 'undefined'.
Started: createAction<P, `${typeof type}/START`>(`${type}/START`),
Pending: createAction(`${type}/PENDING`),
};
};
enum DocActions {
Fetch = 'Fetch',
Delete = 'Delete',
};
export const documentActions = {
Fetch: createAsyncActions<number>()(DocActions.Fetch),
};
const a = documentActions.Fetch.Started(1);
回复:https://replit.com/@AlexanderBausk/VibrantOffbeatChapters#src/main.ts
当我需要 createAction 以返回具有 P 类型有效负载的动作创建者时,我无法正确调用它。 createAction 是有条件类型的,我似乎无法正确处理。我不确定这是否与我尝试使用模板文字类型有关,或者只是我的输入结构不正确。
对于如何以更好的方式实现类型化的动作创建者组的任何帮助或想法,我们将不胜感激。
【问题讨论】:
-
尝试删除显式返回类型。见example。让我知道它是否适合您
标签: typescript redux typescript-generics redux-toolkit