如何在Nuxt 3的useFetch POST请求中指定错误响应类型?
Nuxt3 useFetch指定错误响应类型报错的解决方法
你遇到的问题是因为useFetch的泛型参数顺序使用错误,导致TypeScript无法正确推断请求方法的类型,进而抛出“POST无法分配给method”的错误。
你的原代码:
useFetch<void, ApiResponseError>(this.url, { method: 'POST', body: data, headers: this.headers, onResponseError: this.transformError })
正确实现方式
useFetch的泛型定义中,第二个参数默认是FetchError<unknown>类型,而非直接的自定义错误类型。你需要将自定义错误类型作为FetchError的泛型参数传入,或者调整泛型参数的使用方式:
方法1:正确指定泛型参数
import type { FetchError } from 'ofetch'; useFetch<void, FetchError<ApiResponseError>>(this.url, { method: 'POST', body: data, headers: this.headers, onResponseError: this.transformError })
方法2:在错误回调中做类型断言
如果不想调整泛型,也可以在onResponseError里对响应数据做类型断言:
useFetch<void>(this.url, { method: 'POST', body: data, headers: this.headers, onResponseError: ({ response }) => { const errorData = response._data as ApiResponseError; this.transformError(errorData); } })
原因说明
useFetch的泛型参数顺序为:T(成功响应类型)、E(错误类型,默认是FetchError<unknown>)、ResponseType、Methods等。直接将自定义错误类型作为第二个泛型参数传入,会破坏TypeScript对请求方法的类型推断逻辑,从而引发报错。
内容的提问来源于stack exchange,提问作者Matej
相关产品推荐
相关产品推荐

