TypeScript报错:类型'Awaited<R>'不存在属性'data'问题咨询
TypeScript封装Axios请求函数的类型错误问题
我尝试让自定义的request函数泛型参数与axios.request()保持一致,但遇到了类型检查错误。
代码示例
import axios, { AxiosRequestConfig, AxiosResponse } from 'axios'; async function request<T = any, R = AxiosResponse<T>>(config: AxiosRequestConfig): Promise<R> { const r = await axios.request<T, R>(config); return r; } async function json<T = any, R = AxiosResponse<T>>(config: AxiosRequestConfig): Promise<T> { const response = await request<T, R>(config); return response.data; // TypeScript报错:Property 'data' does not exist on type 'Awaited<R>'.(2339) }
问题详情
- 预期
response的TS类型为AxiosResponse,但实际推断为Awaited<R> - 预期
response.data的类型为T(即AxiosResponse['data']),但TypeScript无法识别该属性
解决方案
问题根源在于R泛型缺少约束——虽然默认值是AxiosResponse<T>,但TypeScript无法保证用户传入的R一定包含data属性。给R添加继承自AxiosResponse<T>的约束即可解决:
import axios, { AxiosRequestConfig, AxiosResponse } from 'axios'; async function request<T = any, R extends AxiosResponse<T> = AxiosResponse<T>>(config: AxiosRequestConfig): Promise<R> { const r = await axios.request<T, R>(config); return r; } async function json<T = any, R extends AxiosResponse<T> = AxiosResponse<T>>(config: AxiosRequestConfig): Promise<T> { const response = await request<T, R>(config); return response.data; // 类型检查通过 }
添加extends AxiosResponse<T>约束后,TypeScript能确定R必然包含data属性,且data类型为T,从而消除错误。
内容的提问来源于stack exchange,提问作者Lin Du
相关产品推荐
相关产品推荐

