【问题标题】:Axios - parse Typescript interfaceAxios - 解析 Typescript 接口
【发布时间】:2020-12-03 22:30:25
【问题描述】:

我想从 typescript 上的 axios 请求中解析数据

我有两个接口

interface Department{
    code: string;
    name: string;
    country: string;
}

interface User {
    name: string;
    email: string;
    departments: Department[];
}

我有一个端点,它返回这样的数据

[
    {
        "name": "Estonia",
        "email": "email",
        "phone": 12345,
        "weight": "60kg",
        "country": "US",
        "departments": [
            {
              "code": 1,
              "name": "depto 1",
              "country": "US"
            },
            {
              "code": 2,
              "name": "depto 2",
              "country": "FR"
            }
        ]
        [...]
    }
]

端点检索到很多我不需要的数据,我只想检索我在接口上定义的属性,这可能吗?

我试过这个,但我得到了所有属性

axios.get<User[]>('http://localhost/users').then(({ data }) => {
        console.log(typeof data, data);
    });

【问题讨论】:

    标签: typescript api parsing axios


    【解决方案1】:

    端点检索到很多我不需要的数据,我只想检索我在接口上定义的属性,这可能吗?

    如果您按照目前axios.get&lt;User[]&gt; 的方式使用它,那么您将只能读取User 接口上存在的属性。

    对象将具有更多属性,但您将无法从 TypeScript 读取/写入它们(没有不安全的类型断言),因此您所拥有的就是我要做的,而不必担心多余的运行时属性。

    【讨论】:

    • 谢谢。基本上我想要做的是修改我在界面中定义的属性并只回复那些。到目前为止,我得到了所有的属性。还有其他方法吗?
    【解决方案2】:

    您可以使用tapi.js - 这是一个专门为此目的的轻量级包。

    在此处阅读the documentation

    【讨论】:

      猜你喜欢
      • 2020-07-26
      • 2016-02-23
      • 2020-04-23
      • 2015-03-11
      • 2021-12-25
      • 2012-09-25
      • 2020-12-17
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多