首页 > 解决方案 > 调用 axios 时出现打字稿错误 - 没有重载匹配此调用

问题描述

我正在调用 axios 并传入一个配置对象,如下所示:

const req = { method, url, timeout: 300000, headers: { 'Content-Type': 'application/json' } }

axios(req)

我收到一个打字稿错误,上面写着“没有重载匹配这个调用”。axios 函数采用以下类型的配置对象AxiosRequestConfig

axios(config: AxiosRequestConfig): AxiosPromise<any>

供您参考,以下是AxiosRequestConfig类型的外观以及Method类型:

interface AxiosRequestConfig {
  url?: string;
  method?: Method;
  baseURL?: string;
  transformRequest?: AxiosTransformer | AxiosTransformer[];
  transformResponse?: AxiosTransformer | AxiosTransformer[];
  headers?: any;
  params?: any;
  paramsSerializer?: (params: any) => string;
  data?: any;
  timeout?: number;
  timeoutErrorMessage?: string;
  withCredentials?: boolean;
  adapter?: AxiosAdapter;
  auth?: AxiosBasicCredentials;
  responseType?: ResponseType;
  xsrfCookieName?: string;
  xsrfHeaderName?: string;
  onUploadProgress?: (progressEvent: any) => void;
  onDownloadProgress?: (progressEvent: any) => void;
  maxContentLength?: number;
  validateStatus?: (status: number) => boolean;
  maxRedirects?: number;
  socketPath?: string | null;
  httpAgent?: any;
  httpsAgent?: any;
  proxy?: AxiosProxyConfig | false;
  cancelToken?: CancelToken;
}

type Method =
  | 'get' | 'GET'
  | 'delete' | 'DELETE'
  | 'head' | 'HEAD'
  | 'options' | 'OPTIONS'
  | 'post' | 'POST'
  | 'put' | 'PUT'
  | 'patch' | 'PATCH'
  | 'link' | 'LINK'
  | 'unlink' | 'UNLINK'

我不明白这个错误,因为我的配置对象似乎很好地满足了这个接口。这就是让我更加困惑的地方:如果我更改了的类型AxiosRequestConfig定义

method?: String;

代替

method?: Method

然后打字稿错误消失了。另外,如果我尝试在我的配置对象中传播并手动添加一个方法属性,如下所示:

axios({...req, method: 'GET'})

错误再次消失。但是我必须添加方法属性...如果我只是在我的配置对象中传播,我会得到与以前相同的错误。

所以看起来错误可能与 AxiosRequestConfig 接口的方法属性有关,但最终我不确定。感谢您的任何帮助。

标签: javascripttypescriptaxios

解决方案


这是一个非常直接的答案。

添加

AxiosRequestConfig

在像这样的导入语句中

import axios, { AxiosRequestConfig, AxiosResponse} from 'axios';

然后在您的配置代码所在的位置下方,只需将AxiosRequestConfig接口分配给您的配置变量,如下所示

const config: AxiosRequestConfig = {
      method: 'get',
      url: `${quickbooksBaseURL}/v3/company/${QuickbooksCustomerID}/invoice/${invoiceID}/pdf?minorversion=${minorVersion}`,
      headers: {
        'Content-Type': 'application/json',
        Authorization: `Bearer ${accessToken}`
      }
    };
    const response: AxiosResponse = await axios(config);

为我做这项工作,我希望它也对你有用。


推荐阅读