【问题标题】:TypeScript interface to catch objects with any amount of values用于捕获具有任意数量值的对象的 TypeScript 接口
【发布时间】:2017-09-17 11:46:33
【问题描述】:

我有一个这样的对象:

{
    "0001": "a",
    "0002": "b",
    "0003": "c",
    ...
}

我可以写一个 TypeScript 接口来描述这个类型吗?

【问题讨论】:

  • 除了{ [key: string]: string } ?

标签: typescript types structural-typing


【解决方案1】:

@NitzanTomer 的评论完全有效:接口映射{ [key: string]: string }

您也可以将其定义为文字,或仅定义为字符串:

interface LiteralInterface { 
    "0001": "a",
    "0002": "b",
    "0003": "c",
     ...
}

interface StringInterface { 
    "0001": string,
    "0002": string,
    "0003": string,
     ...
}

但在这里你必须指定每个属性...

【讨论】:

    【解决方案2】:

    你可以这样实现:

    interface StringInterface {
      [key: string]: string;
    }
    

    【讨论】:

      猜你喜欢
      • 2015-12-29
      • 1970-01-01
      • 2020-12-23
      • 2012-11-04
      • 1970-01-01
      • 1970-01-01
      • 2019-01-07
      • 2020-05-14
      • 2021-09-09
      相关资源
      最近更新 更多