如何在ReactQuery useMutate中使用TypeScript为Axios指定无内容响应的类型?

hpcdzsge  于 2023-08-04  发布在  iOS
关注(0)|答案(1)|浏览(138)

我最近一直在尝试熟悉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)中定义的类型会影响mutateTVariables)的参数中预期的类型?至少我现在是这么看的,也许我没有正确理解错误消息。
任何帮助都是赞赏的,谢谢!

yk9xbfzb

yk9xbfzb1#

请不要将泛型“传递”给useMutation。只需输入mutationFn,并让其余部分被推断出来:

const { mutate, ...actionResults } = useMutation(
    ({param1, param2}: ParamsInterface): Promise<AxiosResponse<null>> => {
      return requestor(Rest.sendRequest(param1, param2))
    },
    {
      onSuccess: () => {
        // do something on success
      },
      onError: (error) => {
        // do something on error
      },
    },
  )

字符串

相关问题