【问题标题】:How can I declare types properly to be able to create groups of redux action creators with shared name parts using createAction?如何正确声明类型以便能够使用 createAction 创建具有共享名称部分的 redux 操作创建者组?
【发布时间】: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


【解决方案1】:

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

【讨论】:

    猜你喜欢
    • 2020-06-08
    • 1970-01-01
    • 2020-11-15
    • 2018-11-22
    • 2019-12-29
    • 1970-01-01
    • 2016-07-30
    • 2021-10-24
    • 2020-02-15
    相关资源
    最近更新 更多