簡體   English   中英

如何在打字稿中正確使用泛型?

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM