我正在将最近使用的钩子转换为类型记录并获得以下错误
(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);
});
};我特别认为它与公理法有关
我以前使用过它,这样我就可以动态地传递各种请求类型。我不知道如何使用最佳的类型记录实践来解决上述错误。
这些值从以下内容中检索
({ url, method, data })P.S:我知道片段中可能还有其他问题,但我会重新考虑这些问题,因为它们只是与类型有关。
发布于 2022-04-22 20:03:02
它之所以抱怨是因为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;https://stackoverflow.com/questions/71973829
复制相似问题