响应数据支持泛型

需求分析

通常情况下,我们会把后端返回数据格式单独放入一个接口中:

  1. // 请求接口数据
  2. export interface ResponseData<T = any> {
  3. /**
  4. * 状态码
  5. * @type { number }
  6. */
  7. code: number
  8. /**
  9. * 数据
  10. * @type { T }
  11. */
  12. result: T
  13. /**
  14. * 消息
  15. * @type { string }
  16. */
  17. message: string
  18. }

我们可以把 API 抽离成单独的模块:

  1. import { ResponseData } from './interface.ts';
  2. export function getUser<T>() {
  3. return axios.get<ResponseData<T>>('/somepath')
  4. .then(res => res.data)
  5. .catch(err => console.error(err))
  6. }

接着我们写入返回的数据类型 User,这可以让 TypeScript 顺利推断出我们想要的类型:

  1. interface User {
  2. name: string
  3. age: number
  4. }
  5. async function test() {
  6. // user 被推断出为
  7. // {
  8. // code: number,
  9. // result: { name: string, age: number },
  10. // message: string
  11. // }
  12. const user = await getUser<User>()
  13. }

接口添加泛型参数

根据需求分析,我们需要给相关的接口定义添加泛型参数。

types/index.ts

  1. export interface AxiosResponse<T = any> {
  2. data: T
  3. status: number
  4. statusText: string
  5. headers: any
  6. config: AxiosRequestConfig
  7. request: any
  8. }
  9. export interface AxiosPromise<T = any> extends Promise<AxiosResponse<T>> {
  10. }
  11. export interface Axios {
  12. request<T = any>(config: AxiosRequestConfig): AxiosPromise<T>
  13. get<T = any>(url: string, config?: AxiosRequestConfig): AxiosPromise<T>
  14. delete<T = any>(url: string, config?: AxiosRequestConfig): AxiosPromise<T>
  15. head<T = any>(url: string, config?: AxiosRequestConfig): AxiosPromise<T>
  16. options<T = any>(url: string, config?: AxiosRequestConfig): AxiosPromise<T>
  17. post<T = any>(url: string, data?: any, config?: AxiosRequestConfig): AxiosPromise<T>
  18. put<T = any>(url: string, data?: any, config?: AxiosRequestConfig): AxiosPromise<T>
  19. patch<T = any>(url: string, data?: any, config?: AxiosRequestConfig): AxiosPromise<T>
  20. }
  21. export interface AxiosInstance extends Axios {
  22. <T = any>(config: AxiosRequestConfig): AxiosPromise<T>
  23. <T = any>(url: string, config?: AxiosRequestConfig): AxiosPromise<T>
  24. }

这里我们先给 AxiosResponse 接口添加了泛型参数 TT=any 表示泛型的类型参数默认值为 any

接着我们为 AxiosPromiseAxios 以及 AxiosInstance 接口都加上了泛型参数。我们可以看到这些请求的返回类型都变成了 AxiosPromise<T>,也就是 Promise<AxiosResponse<T>>,这样我们就可以从响应中拿到了类型 T 了。

demo 编写

examples/extend/app.ts

  1. interface ResponseData<T = any> {
  2. code: number
  3. result: T
  4. message: string
  5. }
  6. interface User {
  7. name: string
  8. age: number
  9. }
  10. function getUser<T>() {
  11. return axios<ResponseData<T>>('/extend/user')
  12. .then(res => res.data)
  13. .catch(err => console.error(err))
  14. }
  15. async function test() {
  16. const user = await getUser<User>()
  17. if (user) {
  18. console.log(user.result.name)
  19. }
  20. }
  21. test()

当我们调用 getUser<User> 的时候,相当于调用了 axios<ResponseData<User>>,也就是我们传入给 axios 函数的类型 TResponseData<User>;相当于返回值 AxiosPromise<T>T,实际上也是 Promise<AxiosResponse<T>> 中的 T 的类型是 ResponseData<User>,所以响应数据中的 data 类型就是 ResponseData<User>,也就是如下数据结构:

  1. {
  2. code: number
  3. result: User
  4. message: string
  5. }

这个也是 const user = await getUser<User>() 返回值 user 的数据类型,所以 TypeScript 能正确推断出 user 的类型。

至此,我们的 ts-axios 接口扩展章节就告一段落了,下一章我们来实现 axios 的一个非常好用的功能 —— 拦截器。