【问题标题】:How to correctly use generics in typescript?如何在打字稿中正确使用泛型?
【发布时间】:2021-12-21 15:47:18
【问题描述】:

我被泛型卡住了。在我的情况下如何正确使用泛型:

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": "类型参数 '{ method: string;网址:字符串;标头:{授权:字符串; }; }' 不能分配给 'string' 类型的参数。",

}"

【问题讨论】:

  • 你说你卡住了,但问题是什么?您的问题是否取决于axios?如果是这样,请将其标记为这样,如果不是,请考虑删除示例代码对它的依赖。这里的目标是让您给我们一个minimal reproducible example,清楚地表明您面临的问题。理想情况下,有人可以将代码放入像The TypeScript Playground (link here!) 这样的独立 IDE 中,然后立即着手解决问题,而无需首先重新创建它。所以应该没有拼写错误、不相关的错误或未声明的类型或值(如axiosapiBaseUrl)。
  • @jcalz 同上。 OP,一旦您描述了您的问题,澄清了您的问题是否取决于 axios,并提供了一个最小的可重现示例,我将很乐意撤销我的反对票。

标签: javascript reactjs typescript generics axios


【解决方案1】:

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

【讨论】:

  • 但是那样的话,会报错:“Untyped function calls may not accept type arguments.”
  • @Puzzle234 你是如何导入 axios 的?你在做类似import axios from "axios"; 的事情吗?你能显示这条线吗?
  • const axios = require("axios");有什么区别?
  • @Puzzle234 你在调用像get 这样的特定函数吗?例如axios.get&lt;Location&gt;( ... )
  • 问题已更新
猜你喜欢
  • 1970-01-01
  • 2021-04-03
  • 2021-05-06
  • 1970-01-01
  • 2015-11-27
  • 1970-01-01
  • 2021-09-27
  • 1970-01-01
  • 2019-03-21
相关资源
最近更新 更多