AxiosStatic 没有索引签名
AxiosStatic has no index signature
我正在将我最近使用的钩子转换为 Typescript 并出现以下错误
(alias) const axios: AxiosStatic
import axios
Element implicitly has an 'any' type because type 'AxiosStatic' has no index signature. Did you mean to call 'axios.get'?ts(7052)
这是从下面的代码产生的。
const fetchData = async () => {
axios[method](url, data, config)
.then((res) => {
setResponse(res.data);
})
.catch((err) => {
setError(err);
})
.finally(() => {
setloading(false);
});
};
我特别相信它与 axios[方法]
有关
我以前用过这个,所以我可以动态传递各种请求类型。我不确定如何使用最佳打字稿实践解决上述错误。
这些值取自下面的
({ url, method, data })
P.S:我知道代码片段中可能还有其他问题,但我会解决这些问题,因为它们只与类型有关。
它在抱怨,因为 method
可能是任何字符串而不是 axios
的键。您可以通过将其类型设置为 axios
.
的键来解决此问题
首先是axios支持的所有方法的联合:
type Methods = "head" | "options" | "put" | "post" | "patch" | "delete" | "get";
那么如果这是一个函数我们可以将参数类型设置为Methods
:
function foo(method: Methods) {
axios[method] // works
// ...
}
或者如果它是一个变量:
let method: Method = ...;
您可能还需要使用强制转换:
let method = ... as Method;
我正在将我最近使用的钩子转换为 Typescript 并出现以下错误
(alias) const axios: AxiosStatic
import axios
Element implicitly has an 'any' type because type 'AxiosStatic' has no index signature. Did you mean to call 'axios.get'?ts(7052)
这是从下面的代码产生的。
const fetchData = async () => {
axios[method](url, data, config)
.then((res) => {
setResponse(res.data);
})
.catch((err) => {
setError(err);
})
.finally(() => {
setloading(false);
});
};
我特别相信它与 axios[方法]
有关我以前用过这个,所以我可以动态传递各种请求类型。我不确定如何使用最佳打字稿实践解决上述错误。
这些值取自下面的
({ url, method, data })
P.S:我知道代码片段中可能还有其他问题,但我会解决这些问题,因为它们只与类型有关。
它在抱怨,因为 method
可能是任何字符串而不是 axios
的键。您可以通过将其类型设置为 axios
.
首先是axios支持的所有方法的联合:
type Methods = "head" | "options" | "put" | "post" | "patch" | "delete" | "get";
那么如果这是一个函数我们可以将参数类型设置为Methods
:
function foo(method: Methods) {
axios[method] // works
// ...
}
或者如果它是一个变量:
let method: Method = ...;
您可能还需要使用强制转换:
let method = ... as Method;