我正在从通用函数中对axios.get
的调用返回AxiosResponse对象.该物体的形状如下:
interface AxiosResponse<T = any, D = any> {
data: T;
...
}
get
电话有这种类型:
get<T = any, R = AxiosResponse<T>, D = any>(url: string, config?: AxiosRequestConfig<D>): Promise<R>;
我花了几个小时寻找解决这个错误的答案:
"Property 'data' does not exist on type 'Awaited<R>
在此代码中(标记错误位置):
export const fetchWithRetry = async <
T = any,
Q = Record<string, string>,
R = AxiosResponse<T>
>(
route: string,
queryParams: Partial<Q> = {},
) => {
const response = await fetchResponseWithRetry<T, Q, R>(route, queryParams)
return response.data; // <= ERROR IS HERE
};
export const fetchResponseWithRetry = async <
T = any,
Q = Record<string, string>,
R = AxiosResponse<T>,
>(
route: string,
queryParams: Partial<Q> = {},
) => {
try {
const options: AxiosRequestConfig = {
headers: {
"Content-Type": "application/json",
},
params: <Q>{ ...queryParams },
};
return (await axios.get<T, R, unknown>(route, options));
} catch (error) {
if (error instanceof Error) {
buildLogger(`${error.message}`);
if (error instanceof AxiosError) buildLogger(`${error.request.url}`);
}
}
throw new Error(`This should never be reached.`);
};
据我了解,4.5中添加了Awaited<R>
类型.我从other answers中了解到,Awaited类型应该解开为R(来自对该问题的公认答案):
如果您正在等待的类型
T
是Promise<U>
,而U
不是任何类型的Promise
,那么Awaited<T>
与U
相同
我该如何解决这个问题?