javascript - 调用 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 接口的方法属性有关,但最终我不确定。感谢您的任何帮助。
解决方案
这是一个非常直接的答案。
添加
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);
为我做这项工作,我希望它也对你有用。
推荐阅读
- c# - .NET 标准库中的实体框架
- karate - afterScenario not working calling features not in the same folder
- javascript - 替换对象数组中的对象属性
- flutter - 将触摸事件推迟到堆栈中的小部件
- google-tag-manager - 无法使用 Google 跟踪代码管理器跟踪表单提交
- typescript - Typescript interface with function called "new"
- javascript - 如何在带有来自动作的道具(MemoizedSelectorWithProps)的选择器的效果中使用 withLatestFrom
- angular - Angular 自定义异步验证器未显示错误
- postman - 跨迭代重用数据
- java - 使用用户名和密码生成访问令牌