简体   繁体   English

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

[英]How to correctly use generics in typescript?

I get stuck with generics .我被泛型卡住了。 How can I correctly use generics in my case :在我的情况下如何正确使用泛型:

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 has typings for this. Axios 有这方面的类型。 It lets you specify a generic type for the axios functions so that result.data will have that generic type.它允许您为 axios 函数指定一个泛型类型,以便result.data将具有该泛型类型。

For example, you can do this:例如,您可以这样做:

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;
};

If you want to make the entire function generic, you can do this:如果你想让整个函数通用,你可以这样做:

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