在TypeScript中使用axios

833 阅读1分钟

在TypeScript中使用axios

  1. 创建文件shims.d.ts,加上泛型
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. 使用方法,在调用时加上自己定义的类型
interface User{
    ...
}
const request = axios.create({
    baseURL: 'http://localhost:3000'
})

const user = () => {
    return request<User>({
        method: 'GET',
        url
    })
}
const user = () => {
    return request.post<User>(url)
}