当前位置:   article > 正文

ts: axios 返回值类型报错 和 解构赋值_axios.d.ts

axios.d.ts

最近做项目用TypeScript发现axios返回值类型一直是any,经过一番Google后, 终于找到了解决办法:新建一个shims-axios.d.ts,重新声明axios模块,然后在调用时加上泛型, 如下:

import axios from 'axios'

declare module 'axios' {
  export interface AxiosInstance {
    <T = any>(config: AxiosRequestConfig): Promise<T>;
    request<T = any> (config: AxiosRequestConfig): Promise<T>;
    get<T = any>(url: string, config?: AxiosRequestConfig): Promise<T>;
    delete<T = any>(url: string, config?: AxiosRequestConfig): Promise<T>;
    head<T = any>(url: string, config?: AxiosRequestConfig): Promise<T>;
    post<T = any>(url: string, data?: any, config?: AxiosRequestConfig): Promise<T>;
    put<T = any>(url: string, data?: any, config?: AxiosRequestConfig): Promise<T>;
    patch<T = any>(url: string, data?: any, config?: AxiosRequestConfig): Promise<T>;
  }
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14

使用:

axios.get<{ data: IBackup[], total: number }>('URL').then(res => {})
  • 1

解构赋值:


let o = {
    a: "foo",
    b: 12,
    c: "bar"
};
let { a, b } = o;
//指定类型
let {a, b}: {a: string, b?: number} = o;
//属性重命名
let { a: newName1, b: newName2 } = o;
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/凡人多烦事01/article/detail/285728
推荐阅读
相关标签
  

闽ICP备14008679号