![](/img/trans.png)
[英]Typescript: How To Use Generics Properly To Infer Return Type of Function Correctly?
[英]How to correctly use generics in typescript?
我被泛型卡住了。 在我的情況下如何正確使用泛型:
export const getEuropeLocations = async (
apiKey: string
): Promise<Location> => {
let response = await axios({
method: "get",
url: `${apiBaseUrl}europe/`,
headers: {
Authorization: `Bearer ${apiKey}`,
},
});
return response.data as Location; // how to return generic here ?
};
Axios 有這方面的類型。 它允許您為 axios 函數指定一個泛型類型,以便result.data
將具有該泛型類型。
例如,您可以這樣做:
import axios from "axios";
export const getEuropeLocations = async (
apiKey: string
) => {
let response = await axios.get<Location>({
method: "get",
url: `${apiBaseUrl}europe/`,
headers: {
Authorization: `Bearer ${apiKey}`,
},
});
return response.data;
};
如果你想讓整個函數通用,你可以這樣做:
export const getEuropeLocations = async <T>(
apiKey: string
) => {
let response = await axios.get<T>({
method: "get",
url: `${apiBaseUrl}europe/`,
headers: {
Authorization: `Bearer ${apiKey}`,
},
});
return response.data;
};
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.