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

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

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

 

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) => AxiosRequestConfig) | undefined' is not assignable to parameter of type '((value: InternalAxiosRequestConfig) => InternalAxiosRequestConfig | Promise>) | null | undefined'.
  Type '(config: AxiosRequestConfig) => AxiosRequestConfig' is not assignable to type '(value: InternalAxiosRequestConfig) => InternalAxiosRequestConfig | Promise>'.
    Type 'AxiosRequestConfig' is not assignable to type 'InternalAxiosRequestConfig | Promise>'.
      Type 'AxiosRequestConfig' is not assignable to type 'InternalAxiosRequestConfig'.
        Types of property 'headers' are incompatible.
          Type 'AxiosHeaders | (Partial & Partial<...>) | undefined' is not assignable to type 'AxiosRequestHeaders'.
            Type 'undefined' is not assignable to type 'AxiosRequestHeaders'.
              Type 'undefined' is not assignable to type 'Partial'.
    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装的是:[email protected]版本。
看来应该是新版本的bug

上官网查看版本信息:

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

 

 

你可能感兴趣的:(解决报错,前端,javascript)