赞
踩
我在ts项目中使用axios时,遇到两个困惑
针对以上两三点做了以下封装
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) } }
在上面做的一个补充之外,还可以正常做axios的拦截器
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。