繁体   English   中英

调用 axios 时出现 Typescript 错误 - 没有与此调用匹配的过载

[英]Typescript error while calling axios - no overload matches this call

我正在调用 axios 并传入配置 object ,如下所示:

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

axios(req)

我收到 typescript 错误,提示“没有与此调用匹配的过载”。 axios function 采用 AxiosRequestConfig 类型的配置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'

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

method?: String;

代替

method?: Method

然后 typescript 错误消失。 此外,如果我尝试在我的配置 object 中传播并手动添加如下方法属性:

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

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

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

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

添加

AxiosRequestConfig

在像这样的导入语句中

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

然后 go 在您的配置代码所在的位置下方,然后将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);

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM