You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Redux Toolkit中usePostCarMutation返回的postCar参数类型是什么?

正确的Redux-Toolkit Mutation触发函数类型标注方法

你可以通过以下两种方式正确标注postCar的类型:

方法一:从钩子返回值提取类型

直接利用ReturnType工具类型,从usePostCarMutation的返回值中获取第一个元素的类型(也就是触发函数的类型):

import { usePostCarMutation } from './path-to-your-api-slice';

// 定义子组件的Props类型
type AddCarFormProps = {
  postCar: ReturnType<typeof usePostCarMutation>[0];
};

// 在子组件中使用
const AddCarForm = ({ postCar }: AddCarFormProps) => {
  // ...组件逻辑
};

方法二:从API切片类型中提取

RTK Query会为每个endpoint自动生成对应的类型,你可以直接从API切片的类型中获取触发函数类型:

import type { YourApiSliceType } from './path-to-your-api-slice';

// 提取postCar的触发函数类型
type PostCarTrigger = YourApiSliceType['endpoints']['postCar']['trigger'];

type AddCarFormProps = {
  postCar: PostCarTrigger;
};

为什么之前的尝试失败:

  • 尝试1:typeof api.endpoints.postCar是mutation的定义对象类型,不是实际调用的触发函数类型
  • 尝试2:MutationDefinition是mutation的元定义类型,并非触发函数类型
  • 尝试3:MutationDefinition的泛型参数顺序错误,正确顺序应为MutationDefinition<ResultType, QueryArg, BaseQueryFn, TagTypes, EntityTypes>,你颠倒了Car(返回值)和CarEndpointPostParams(入参)的位置,且手动指定泛型不如自动提取准确

内容的提问来源于stack exchange,提问作者axel

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.15 18:14:56