我正在將我最近使用的鉤子轉換為 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[method] 有關
我以前使用過這個,所以我可以動態地傳遞各種請求型別。我不確定如何使用最佳打字稿實踐來解決上述錯誤。
這些值是從以下內容中檢索到的
({ url, method, data })
PS:我知道片段中可能存在其他問題,但我會解決這些問題,因為它們僅與型別有關。
uj5u.com熱心網友回復:
它正在抱怨,因為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://www.uj5u.com/qiye/461787.html
標籤:javascript 反应 打字稿 反应钩子
