首页 > 解决方案 > 我可以使用 TypeScript 在 axios.get 方法中指定泛型类型的任何类型

问题描述

axios.get('/api')

当我像上面那样使用 TypeScript 编码时,我应该更好地指定类型,因为我可以引用 axios 的类型定义,如下所示。

(method) AxiosInstance.get<any, AxiosResponse<any>>(url: string, config?: AxiosRequestConfig | undefined): Promise<AxiosResponse<any>>
                           ^^^ <- ???

我无法理解any第一种通用类型的 get 方法的类型AxiosInstance.get<any,。这个any要干什么用?

标签: javascripttypescriptaxiostypescript-generics

解决方案


看看axios 类型定义

get<T = any, R = AxiosResponse<T>>(url: string, config?: AxiosRequestConfig): Promise<R>;

第一个类型参数是 api 返回的类型。这默认为任何。

二是响应类型。这默认为带有第一个参数的类型的响应。


推荐阅读