如何使类型适合于各种返回类型

时间:2019-02-06 14:10:47

标签: typescript

我使用REST库下载名为Axios的数据,并且它以称为AxiosResponse的类型返回数据,如下所示:

export interface AxiosResponse<T = any>  {
  data: T;
  ...
}

返回的数据可以是不同的类型。如何为返回值分配类型类型,以便在使用时是类型安全的?

也就是说,我的呼叫看起来像:

axios({...}).then(a=> {setResult(a.data)})

其中a.data在一种情况下的形状将与另一种情况不同。只说这个实例,我希望数据是

interface car {
   model: string
   cost: number
}  

1 个答案:

答案 0 :(得分:2)

在默认定义中,没有指定返回类型的好方法。您所能做的就是用作类型断言:

axios("").then((a => a.data as car)

http动词特定版本允许类型参数,因此效果更好:

axios.get<car>("").then(a=> {a.data}) // a.data is car

如果需要,可以扩展定义的原始版本以接受类型参数(可以将此声明放在项目中的某个位置:

import axios, { AxiosPromise } from 'axios'

declare module 'axios' {
    export interface AxiosInstance {
        <T>(config: AxiosRequestConfig): AxiosPromise<T>;
        <T>(url: string, config?: AxiosRequestConfig): AxiosPromise<T>;
    }
}
interface car {
    model: string
    cost: number
}

axios<car>("").then(a => a.data)