【问题标题】:Mapping fields from response in Axios?从 Axios 中的响应映射字段?
【发布时间】:2021-05-14 10:12:45
【问题描述】:

我有以下代码:

axios.get<Response>(url)
  .then(response => {
    console.log(response.data);
  }).catch(error => {
  // handle error
  console.log(error);
});

JSON 响应包含我无法在 TypeScript 中表达的字段:

{ 
    "field:Type": "foo"
}

like: name:Type 包含 string - 在我的例子中是 "foo"

如何在Response 接口中映射此类字段以便以后使用?

interface Response {
    myMappedField: string;
}

【问题讨论】:

    标签: json typescript axios mapping


    【解决方案1】:

    在打字稿中,你必须用单引号括起来,

    interface Response {
      myMappedField?: string;
     'field:Type'?: string;
    }
    

    在 axios 响应对象中,您可以使用点/括号符号来读取属性。

    response.data['field:Type']
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2023-03-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-05-05
      • 2021-12-25
      • 1970-01-01
      • 2021-12-02
      相关资源
      最近更新 更多