最近做项目用TypeScript发现axios返回值类型一直是any,经过一番Google后, 终于找到了解决办法:新建一个shims.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>;
}
}
使用
import { IBackup } from '@/types/backup.types'
export const getBackups = (params: any) =>
request<{ data: IBackup[], total: number }>({
url: '/backups',
method: 'get',
params
})
或者
axios.get<{ data: IBackup[], total: number }>('URL').then(res => {})
网友评论