【问题标题】:TypeScript: correct typing for return type of AsyncThunk when using 'unwrapResult' of Redux ToolkitTypeScript:使用 Redux Toolkit 的“unwrapResult”时,正确键入 AsyncThunk 的返回类型
【发布时间】:2021-07-11 15:00:47
【问题描述】:

我正在努力为我的 AsyncThunkAction 的返回类型找到正确的类型,以便将它与 Redux Toolkit 的 unwrapResult 方法一起使用(请参阅:Redux Tookit: Unwrapping Result Actions):

在 Slice 中声明异步 thunk:

export
 const createChannel = createAsyncThunk<
  { id: string },
  ChannelReqDto,
  InjectedAxiosClientType
>("channel/createChannel", async (req, thunkApi) => {
  const result = await thunkApi.extra.client.post(
    `/store/${req.storeId}/channels`,
    {
      category: req.category,
      group: req.group,
      name: req.name,
      rules: [],
    }
  );
  return result.data;
});

在 React 组件中的使用:

const newChannel = await dispatch(
    createChannel({
        name: name,
        group: group,
        category: category,
        storeId: storeIdParam,
        rules: [],
    })
);
const result = unwrapResult(newChannel);

TypeScript 错误:

TS2345: Argument of type 'AsyncThunkAction<{ id: string; }, ChannelReqDto, InjectedAxiosClientType>' is not assignable to parameter of type 'UnwrappableAction'.   Property 'payload' is missing in type 'AsyncThunkAction<{ id: string; }, ChannelReqDto, InjectedAxiosClientType>' but required in type 'UnwrappableAction'.

结果类型需要扩展接口UnwrappableAction,但不知怎的,如果没有 ts-ignore,我无法让它工作:

export declare function unwrapResult<R extends UnwrappableAction>(action: R): UnwrappedActionPayload<R>;

【问题讨论】:

    标签: typescript redux redux-toolkit


    【解决方案1】:

    @acemarke 在 Reactiflux 聊天中给了我答案:

    我必须使用在 redux 存储中理想地声明的类型化调度(在我的例子中是 store.tsx):

    export type AppDispatch = typeof store.dispatch;
    export const useAppDispatch = () => useDispatch<AppDispatch>();
    
    • store.dispatch() 默认返回你传入的action
    • 中间件可以修改返回值并换成其他东西
    • thunk 中间件通过返回 thunk 函数返回的任何内容来实现这一点
    • 基本 Dispatch 类型不知道已安装 thunk 中间件,因此它认为它会返回您传入的任何内容 - 在本例中,是 thunk 函数本身
    • thunk 函数绝对不是“不可打包”的,也没有有效载荷字段
    • 切换到自定义的 AppDispatch 类型意味着 TS 现在可以识别“调度的返回类型是这个 thunk 函数返回的任何内容”

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-01-22
      • 1970-01-01
      • 2019-09-02
      • 2021-05-28
      • 2021-02-23
      • 2020-06-04
      相关资源
      最近更新 更多