typescript 类型的参数不能分配给类型为“CreateAxiosDefaults”的参数

5sxhfpxr  于 2023-08-07  发布在  TypeScript
关注(0)|答案(1)|浏览(325)

我正在使用Node和Typescript创建一个库。我的api.ts文件中有此代码

import axios, { AxiosInstance } from 'axios'
import {
  IAxiosStruct,
  BaseError,
  BASE_URL,
  excludeFields,
  handleAxiosError,
} from './utils'

export class TermiiCore {
  public request: AxiosInstance

  constructor(public apiKey: string) {
    this.apiKey = apiKey
    this.request = axios.create({
      baseURL: BASE_URL,
      headers: {
        Accept: 'application/json',
        'Content-Type': 'application/json',
      },
    })
  }

  public async useRequest(req: IAxiosStruct) {
    try {
      const customHeaders = excludeFields(
        ['common', 'delete', 'get', 'head', 'put', 'patch', 'post'],
        this.request.defaults.headers
      )

      const getUrl = this.request.defaults.baseURL
      const requestInstance = await axios.request({
        url: `${getUrl}${req.url}`,
        method: req.method,
        headers: customHeaders,
        data: req.data,
      })
      return requestInstance
    } catch (error) {
      throw new BaseError({ message: handleAxiosError(error) })
    }
  }
}

字符串
message.ts中使用

import { TermiiCore } from '../../api'
import { BaseError, handleAxiosError } from '../../utils'
import { SendMessageDto } from './message.dto'

export class Message extends TermiiCore {
  constructor(apiKey: string) {
    super(apiKey)
  }
  public async sendSMS(data: SendMessageDto) {
    try {
      const requestObj = {
        method: 'POST',
        url: `/sms/send`,
        data,
      }

      const response = await this.useRequest(requestObj)
      return response
    } catch (error) {
      throw new BaseError({ message: handleAxiosError(error) })
    }
  }
}


但是,当我运行pnpm run build时,我得到

Argument of type '{ baseURL: string; headers: { Accept: string; 'Content-Type': string; }; }' is not assignable to parameter of type 'CreateAxiosDefaults<any>'.
  Property 'string' is missing in type '{ baseURL: string; headers: { Accept: string; 'Content-Type': string; }; }' but required in type 'CreateAxiosDefaults<any>'.


我不知道是什么问题,我已经尝试了不同的方法,但没有工作到目前为止。
这里是code

yzuktlbb

yzuktlbb1#

由于axios的次要版本4(从1.3.x1.4.x),这个问题似乎正在发生。我自己也试着弄明白了,看到了axios的changelog,但这两个版本之间唯一的区别是后者导出了一个类型。
更改为1.3.x版本应该可以成功编译库。

相关问题