Axios请求方法的静态类型

tcbh2hod  于 12个月前  发布在  iOS
关注(0)|答案(1)|浏览(120)

在我的实用程序方法中,我使用了Axios请求方法,如下所示:

const response = await axios[method](url, body);

字符串
其中参数符合接口

import { Method } from 'axios';

interface UseRequestProps {
  url: string;
  method: Lowercase<Method>;
  body: any;
}


虽然method参数被缩小到

UseRequestProps.method: "get" | "delete" | "head" | "options" | "post" | "put" | "patch" | "purge" | "link" | "unlink"


我还是有错误

TS7052: Element implicitly has an any type because type AxiosStatic has no index signature. Did you mean to call axios.get


当我将method参数定义为具有较少请求类型的联合类型时,不会发生这种情况:

interface UseRequestProps {
  url: string;
  method: "get" | "delete" | "head" | "options" | "post" | "put" | "patch";
  body: any;
}


这两个版本之间有什么区别?我如何让第一个版本工作?

csbfibhn

csbfibhn1#

方法"purge" | "link" | "unlink"不在Axios请求类型上。解决方案是将Method和Axios请求类型交叉,

interface UseRequestProps {
  ...
  method: Lowercase<Method> & keyof typeof axios;
  ...
}

字符串

相关问题