当前位置:   article > 正文

使用ts封装axios时增加的一些类型判断_axios 类型新增

axios 类型新增

我在ts项目中使用axios时,遇到两个困惑

  1. 在定义接口时,写method选项没有提示,容易写错
  2. 写拦截器时针对自己定义的一些配置选项没有提示或编译报错
  3. 接口返回的数据没有类型提示

针对以上两三点做了以下封装

import axios from 'axios'
import type { InternalAxiosRequestConfig, AxiosResponse, Method, AxiosRequestConfig } from 'axios'
//创建axios实例
const service = axios.create({
  timeout: 20000,
  baseURL: '/test',
  headers: { 'Content-Type': 'application/json;charset=utf-8' }
})

declare module 'axios' {
//这里扩展里InternalAxiosRequestConfig类型
  interface InternalAxiosRequestConfig<D = any> {
    loading?: boolean
    method: Method
  }
}

//请求拦截器
service.interceptors.request.use(
  //这里的config不能使用自己的类型,因为源码里写死了InternalAxiosRequestConfig类型
  //使用自己的类型,编译会报错
  (config: InternalAxiosRequestConfig) => {
    //这里config.loading是会有提示,不会报错的
    return config
  },
  (error: any) => {
    return Promise.reject(error)
  }
)



/**
* 这里使用了Omit类型,排除了InternalAxiosRequestConfig的必填选项headers
 * 这个函数有两个作用
 * 1.限制method选项的类型,同时编译器也会对method的值有提示
 * 2.对返回数据做了类型推断
 */
export function fetchApi<T = any, R = BaseResult, D = any>(
  config: Omit<InternalAxiosRequestConfig<D>, 'headers'>
): Promise<R> {
  return service<T, R, D>(config)
}
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44

在上面做的一个补充之外,还可以正常做axios的拦截器

本文内容由网友自发贡献,转载请注明出处:【wpsshop博客】
推荐阅读
相关标签
  

闽ICP备14008679号