如何正确声明类型,以便能够使用createAction创建具有共享名称部分的redux操作创建者组



我正在尝试使用模板文字类型来创建Redux操作的类型化组,如"FETCH/START"FETCH/PPENDING";,等

我想使用@reduxjs/toolkitcreateAction来制作我的动作创作者,比如:

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/VibrantOffbeat章节#src/main.ts

当我需要createAction返回一个有效载荷为p类型的动作创建者时,我无法正确调用它。createAction是有条件类型的,我似乎无法正确执行。我不确定这是否与我试图使用模板文字类型有关,或者只是不正确地构建了我的类型。

对于如何以更好的方式实现类型化的动作创作者群体,我们将不胜感激。

我的第一个答案是不要试图自己生成这样的操作。相反,使用Redux Toolkit中的createAsyncThunkAPI来处理与异步请求相关的创建和调度操作。这应该会消除您在这里获得的几乎所有代码。

最新更新