需求
通常情况下,我们会把后端返回数据格式单独放入一个接口中:
// 请求接口数据
export interface ResponseData<T = any> {
/**
* 状态码
* @type { number }
*/
code: number
/**
* 数据
* @type { T }
*/
result: T
/**
* 消息
* @type { string }
*/
message: string
}
我们可以把API抽成单独的模块:
import { ResponseData } from './interface.ts';
export function getUser<T>() {
return axios.get<ResponseData<T>>('/somepath')
.then(res => res.data)
.catch(err => console.error(err))
}
接口添加泛型参数
interface AxiosResponse<T = any> {
status: number,
statusText: string,
config: AxiosRequestConfig,
headers: any,
// 本来想说要定义成XMLHttpRequest,但是官方的axios是node端也适用的,
// 那么在node端,就不是XMLHttpRequest类型了,所以在此纠正过来
request: any,
// request: XMLHttpRequest,
data: T
}
interface AxiosPromise<T = any> extends Promise<AxiosResponse<T>> {}
interface Axios {
request<T = any>(config: AxiosRequestConfig): AxiosPromise<T>
get<T = any>(url: string, config?: AxiosRequestConfig): AxiosPromise<T>
head<T = any>(url: string, config?: AxiosRequestConfig): AxiosPromise<T>
delete<T = any>(url: string, config?: AxiosRequestConfig): AxiosPromise<T>
options<T = any>(url: string, config?: AxiosRequestConfig): AxiosPromise<T>
put<T = any>(url: string, data?: any, config?: AxiosRequestConfig): AxiosPromise<T>
post<T = any>(url: string, data?: any, config?: AxiosRequestConfig): AxiosPromise<T>
patch<T = any>(url: string, data?: any, config?: AxiosRequestConfig): AxiosPromise<T>
}
interface AxiosInstance extends Axios {
<T = any>(config: AxiosRequestConfig): AxiosPromise<T>
<T = any>(url: string, config?: AxiosRequestConfig): AxiosPromise<T>
}
demo
import axios from '../../src/index'
interface ResponseData<T = any> {
result: T,
code: string,
message: string
}
interface User {
name: string,
age: number
}
function getUser<T>() {
return axios<ResponseData<T>>('/api/extend/get')
}
getUser<User>().then(res => {
console.log('res', res)
})
添加这样一个对泛型的支持,其实在程序运行的时候,不会有什么左右,猜想可能是能够在使用的时候,允许应用方通过这个泛型的定义,来声明期望得到的数据类型吧
网友评论