首页 > 其他分享 >用TS封装Axios遇到的奇怪问题

用TS封装Axios遇到的奇怪问题

时间:2023-03-17 09:01:52浏览次数:41  
标签:assignable Axios 封装 Type TS InternalAxiosRequestConfig axios type AxiosRequestCo

按照王红元课程中的代码去封装,出现这个错误。

// 一、实例拦截器: 从config中取出的拦截器是对应的实例的拦截器
    this.instance.interceptors.request.use(
      this.interceptors?.requestInterceptor,
      this.interceptors?.requestInterceptorCatch
    )
TS2345: Argument of type '((config: AxiosRequestConfig<any>) => AxiosRequestConfig<any>) | undefined' is not assignable to parameter of type '((value: InternalAxiosRequestConfig<any>) => InternalAxiosRequestConfig<any> | Promise<InternalAxiosRequestConfig<any>>) | null | undefined'.   Type '(config: AxiosRequestConfig<any>) => AxiosRequestConfig<any>' is not assignable to type '(value: InternalAxiosRequestConfig<any>) => InternalAxiosRequestConfig<any> | Promise<InternalAxiosRequestConfig<any>>'.     Type 'AxiosRequestConfig<any>' is not assignable to type 'InternalAxiosRequestConfig<any> | Promise<InternalAxiosRequestConfig<any>>'.       Type 'AxiosRequestConfig<any>' is not assignable to type 'InternalAxiosRequestConfig<any>'.         Types of property 'headers' are incompatible.           Type 'AxiosHeaders | (Partial<RawAxiosHeaders & { Accept: AxiosHeaderValue; "Content-Length": AxiosHeaderValue; "User-Agent": AxiosHeaderValue; "Content-Encoding": AxiosHeaderValue; Authorization: AxiosHeaderValue; } & { ...; }> & Partial<...>) | undefined' is not assignable to type 'AxiosRequestHeaders'.             Type 'undefined' is not assignable to type 'AxiosRequestHeaders'.               Type 'undefined' is not assignable to type 'Partial<RawAxiosHeaders & { Accept: AxiosHeaderValue; "Content-Length": AxiosHeaderValue; "User-Agent": AxiosHeaderValue; "Content-Encoding": AxiosHeaderValue; Authorization: AxiosHeaderValue; } & { ...; }>'.

肯定是类型的问题。但仔细检查核对,代码跟王老师的一样。
经过仔细看提示信息,发现一层一层的错误可能是 Axios自己的类型定义可能有问题。因为提示信息一层一层到最后是
AxiosHeaders 不能赋给AxiosRequestHeaders。这个问题已经跟我们自己写的代码没有关系了。于是抱着试试看的想法
输入:yarn add axios@next
问题竟然神奇的解决了。
为了确认,我重新输入:yarn add axios
这里装的是:[email protected]版本
问题又一次出现。
再来:yarn add axios@next
问题又解决。
经过对比:加上next装的是:[email protected]版本。
看来应该是新版本的bug
上官网查看版本信息:

1.2.3版本似乎提到了这个问题。装上之后,果然可以用,但经过测试1.2.4后的版本都不行。

标签:assignable,Axios,封装,Type,TS,InternalAxiosRequestConfig,axios,type,AxiosRequestCo
From: https://www.cnblogs.com/xiaolee-tech/p/17225357.html

相关文章