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

最近做项目用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>;
  }
}

使用:

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

解构赋值:


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;

你可能感兴趣的:(typescript,javascript,前端)