【问题标题】:JS or TS - Getting the keys of a interfaceJS 或 TS - 获取接口的键
【发布时间】:2019-09-02 04:48:02
【问题描述】:

假设我有一个类似的界面:

export interface Album{
    id: string,
    code: string,
    title: string,
    description: string,
    publisher: string,
}

(实际上很长 - 我只是在这里简化了)。 无论如何,我想创建一个像这样的对象:

const columnSpecs = {
        "id": {  "title": "ID", "width": 300 },
        "code": { "title": "Code", "width": 150 },
        "title": { "title": "Title", "width": 150 },
        "description": { "title": "Description", "width": 150 },
        "publisher": { "title": "Publisher", "width": 150 },
};

现在我自己写columnSpecs,但是如果该接口发生变化,我需要更新对象columnSpecs

有没有办法拉出接口键,这样我就可以遍历我拥有的任何接口,然后自己制作对象?

谢谢。

【问题讨论】:

  • 接口只在编译时存在,所以不 - 你不能在运行时获取它的键

标签: javascript typescript object ecmascript-6


【解决方案1】:

使用Object.keys提取密钥:

Object.keys(albumVar).forEach(key => {...});

【讨论】:

  • albumVar 是什么?
  • Album 类型的变量。
猜你喜欢
  • 1970-01-01
  • 2020-11-18
  • 2022-11-03
  • 2021-06-28
  • 2019-08-03
  • 1970-01-01
  • 2020-03-23
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多