【问题标题】:any type of I can designate in generic types in axios.get method with TypeScript我可以使用 TypeScript 在 axios.get 方法中指定泛型类型的任何类型
【发布时间】:2019-12-12 04:23:01
【问题描述】:
axios.get('/api')

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

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

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

【问题讨论】:

  • 而不是any,你应该把这个请求返回的模型/数据的类型放在那里;比如axios.get&lt;IUser&gt;('/api/user/12345'),第二个类型留空。也许根本不把第二个类型放在那里会更好,而是将方法描述为get&lt;T = any&gt;(url: string, config?: AxiosRequestConfig): Promise&lt;AxiosResponse&lt;T&gt;&gt;;

标签: javascript typescript axios typescript-generics


【解决方案1】:

看看axios type definitions

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

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-06-03
    • 2021-06-18
    • 2019-05-30
    • 2011-12-11
    • 1970-01-01
    相关资源
    最近更新 更多