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
相关产品推荐
相关产品推荐

