我最近一直在尝试熟悉ReactQuery和TypeScript,并基于useMutation
的签名:function useMutation<TData = unknown, TError = unknown, TVariables = void, TContext = unknown>
个
我的理解是这样的:
TData
是调用mutate
时返回的结果的类型。TError
是错误时的错误响应类型。TVariables
是传递给mutate
的参数的类型
我目前正在尝试创建一个钩子,它将发布到一个端点,如果成功,将返回一个204 No Content响应,所以我尝试了这个:
const { mutate, ...actionResults } = useMutation<
AxiosResponse<null>, // <-- I put null here because I expect a 204 no content response
AxiosError<ErrorResponseType>,
ParamsInterface
>(
({param1, param2}: ParamsInterface) => { // Having null above gives me an error on this line, see details below.
return requestor(Rest.sendRequest(param1, param2))
},
{
onSuccess: () => {
// do something on success
},
onError: (error) => {
// do something on error
},
},
)
字符串
上面评论中提到的错误是:
Overload 1 of 4, '(mutationFn: MutationFunction<AxiosResponse<null>, ParamsInterface>, options?: Omit<UseMutationOptions<AxiosResponse<null>, AxiosError<ErrorResponseType>, ParamsInterface, unknown>, "mutationFn">): UseMutationResult<...>', gave the following error.
Argument of type '({ param1, param2 }: ParamsInterface) => AxiosPromise<object>' is not assignable to parameter of type 'MutationFunction<AxiosResponse<null>, ParamsInterface>'.
Call signature return types 'AxiosPromise<object>' and 'Promise<AxiosResponse<null>>' are incompatible.
The types of 'then' are incompatible between these types.
Type '<TResult1 = AxiosResponse<object>, TResult2 = never>(onfulfilled?: (value: AxiosResponse<object>) => TResult1 | PromiseLike<TResult1>, onrejected?: (reason: any) => TResult2 | PromiseLike<...>) => Promise<...>' is not assignable to type '<TResult1 = AxiosResponse<null>, TResult2 = never>(onfulfilled?: (value: AxiosResponse<null>) => TResult1 | PromiseLike<TResult1>, onrejected?: (reason: any) => TResult2 | PromiseLike<...>) => Promise<...>'.
Types of parameters 'onfulfilled' and 'onfulfilled' are incompatible.
Types of parameters 'value' and 'value' are incompatible.
Type 'AxiosResponse<object>' is not assignable to type 'AxiosResponse<null>'.
Type 'object' is not assignable to type 'null'.
型
上面的错误通过保留AxiosResponse
未类型化而消失,我假设它保留默认的any
类型。
为什么响应(TData
)中定义的类型会影响mutate
(TVariables
)的参数中预期的类型?至少我现在是这么看的,也许我没有正确理解错误消息。
任何帮助都是赞赏的,谢谢!
1条答案
按热度按时间yk9xbfzb1#
请不要将泛型“传递”给
useMutation
。只需输入mutationFn
,并让其余部分被推断出来:字符串