我正在调用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'})
错误再次消失。但是我必须在...中添加method属性,如果我只是散布在配置对象中,则会得到与以前相同的错误。
因此,似乎该错误可能与AxiosRequestConfig接口的method属性有关,但最终我不确定。谢谢您的帮助。