调用 axios 时出现打字稿错误 - 没有重载与此调用匹配

jer*_*rfp 9 javascript typescript axios

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

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

axios(req)

Run Code Online (Sandbox Code Playgroud)

我收到一个打字稿错误,显示“没有重载与此调用匹配”。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'
Run Code Online (Sandbox Code Playgroud)

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

method?: String;
Run Code Online (Sandbox Code Playgroud)

代替

method?: Method
Run Code Online (Sandbox Code Playgroud)

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

axios({...req, method: 'GET'})
Run Code Online (Sandbox Code Playgroud)

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

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

Raj*_*hil 12

这是一个非常简单的答案。

添加

Axios请求配置

在你的导入声明中像这样

import axios, { AxiosRequestConfig, AxiosResponse} from 'axios';
Run Code Online (Sandbox Code Playgroud)

然后转到您的配置代码所在的位置,然后将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);
Run Code Online (Sandbox Code Playgroud)

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