我被泛型卡住了。在我的情況下,如何正確使用泛型:
export interface Location {
id: number;
address: {
houseNumber: string;
};
}
export const getEuropeLocations = async (
apiKey: string
) => {
let response = await axios.get<Location>({
method: "get",
url: `${apiBaseUrl}europe/`,
headers: {
Authorization: `Bearer ${apiKey}`,
},
});
return response.data;
};
型別有錯誤:“{“message”:“型別'{方法的引數:字串;網址:字串;標頭:{ 授權:字串;}; }' 不能分配給 'string' 型別的引數。",
}"
uj5u.com熱心網友回復:
Axios 有這方面的型別。它允許您為 axios 函式指定一個泛型型別,以便result.data具有該泛型型別。
例如,您可以這樣做:
import axios from "axios";
export const getEuropeLocations = async (
apiKey: string
) => {
let response = await axios.get<Location>(`${apiBaseUrl}europe/`, {
headers: {
Authorization: `Bearer ${apiKey}`,
},
});
return response.data;
};
如果你想讓整個函式通用,你可以這樣做:
export const getEuropeLocations = async <T>(
apiKey: string
) => {
let response = await axios.get<T>(`${apiBaseUrl}europe/`, {
headers: {
Authorization: `Bearer ${apiKey}`,
},
});
return response.data;
};
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/353351.html
標籤:javascript 反应 打字稿 泛型 公理
上一篇:有沒有辦法在ChakraUI選項卡組件中強制卸載選項卡?
下一篇:我正在使用CocktailDBAPI制作一個React應用程式,但axios不會執行GET請求。瀏覽器獲取資源沒有問題
