解决:用TS封装Axios报错TS2345:Argument of type ‘((config: AxiosRequestConfig<any>) => AxiosRequestConfig...

 代码没问题,但是一直报红线。

 

class SYRequest {
  instance: AxiosInstance
  interceptors?: SYRequestInterceptors

  constructor(config: SYRequestConfig) {
    this.instance = axios.create(config)
    this.interceptors = config.interceptors

    // 从 config 中取出的拦截器是对应的实例的拦截器
    this.instance.interceptors.request.use(
      this.interceptors?.requestInterceptor,
      this.interceptors?.requestInterceptorCatch
    )

 运行后报错,研究发现是axios的版本问题

ERROR in src/service/request/request.ts:26:7
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; } & { ...; }>'.
    24 |     // 从 config 中取出的拦截器是对应的实例的拦截器
    25 |     this.instance.interceptors.request.use(
  > 26 |       this.interceptors?.requestInterceptor,
       |       ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
    27 |       this.interceptors?.requestInterceptorCatch
    28 |     )
    29 |     this.instance.interceptors.response.use(

解决方法:

yarn add axios@next
加上next装的是:axios@1.2.0-alpha.1版本。
看来应该是新版本的bug

上官网查看版本信息:

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

 

 

  • 3
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值