Pat*_*nny 2 typescript axios typescript4.0
我有一个用 TypeScript 编写的 Ionic React 应用程序。今天早上尝试升级到 4.8 时,我收到了Object is of type \'unknown\'.Axios 响应。
这段代码在 4.7 中运行良好,但 TypeScript 4.8 拒绝构建我的应用程序。
\n这是有问题的代码:
\nconst handleErrorsPostAuth = (error: AxiosError) => {\n if (error?.response) {\n // Object is of type \'unknown\' for the line below.\n if (error.response.data.errors[0]) {\n // Object is of type \'unknown\' for the line below.\n throw new Error(error.response.data.errors[0].detail);\n }\n throw new Error(error.response.toString());\n }\n throw new Error(error.message);\n};\nRun Code Online (Sandbox Code Playgroud)\n我阅读了TypeScript 4.8 发行说明,发现lib.d.ts 更新的重大更改包括:
\n\n\n虽然 TypeScript 努力避免重大中断,但即使内置库中的微小更改也可能会导致问题。我们不希望 DOM 和 lib.d.ts 更新导致\xe2\x80\x99 出现重大中断,但一个值得注意的变化是\nErrors 上的 Cause 属性现在具有未知类型,而不是\nError。
\n
我的问题是response,而不是cause,所以我不确定这是否是我遇到的问题。
这是AxiosResponseaxios index.d.ts的接口:
export interface AxiosResponse<T = any, D = any> {\n data: T;\n status: number;\n statusText: string;\n headers: AxiosResponseHeaders;\n config: AxiosRequestConfig<D>;\n request?: any;\n}\nRun Code Online (Sandbox Code Playgroud)\n我尝试添加instanceof这样的检查:
if (error?.response && error.response instanceof AxiosResponse) {\nRun Code Online (Sandbox Code Playgroud)\n但这不起作用,因为它AxiosResponse是一个接口,而且似乎没有办法检查一个对象是否实现了 TypeScript 中的接口,只能检查一个对象是否属于给定类型。
那么,我现在如何正确检查 axios 响应呢?这可能是显而易见的,但我并不真正理解 axios 类型是如何工作的——我认为我需要缩小类型以确保我有一个 AxiosResponse 并且不是未知的,但我不知道该怎么做。
\n正如我们在这里看到的,AxiosError 是一个通用的https://github.com/axios/axios/blob/bdf493cf8b84eb3e3440e72d5725ba0f138e0451/index.d.ts#L276
其中 T 默认未知。T 用于创建响应的类型 https://github.com/axios/axios/blob/bdf493cf8b84eb3e3440e72d5725ba0f138e0451/index.d.ts#L288
所以你应该能够做这样的事情:
type MyErrorResponse = {
errors: {detail: string}[]
}
const handleErrorsPostAuth = (error: AxiosError<MyErrorResponse>) => {
if (error?.response) {
// Object is of type 'unknown' for the line below.
if (error.response.data.errors[0]) {
// Object is of type 'unknown' for the line below.
throw new Error(error.response.data.errors[0].detail);
}
throw new Error(error.response.toString());
}
throw new Error(error.message);
};
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
4059 次 |
| 最近记录: |