【问题标题】:Dynamic tag in JSONJSON 中的动态标签
【发布时间】:2020-08-02 02:58:45
【问题描述】:

我正在生成一个 JSON 文件,并且我在 TypeScript 中有一个以下类型的变量:

export interface Rules{
  name: string,
  condition: string,
}

我想以以下格式解析 JSON 中的“规则”类型:

"dataRetentionRules": {
    "RULE_1": {
        "name": "test123",
             "condition": "RetentionStartDate"
        },
    "RULE_2": {
        "name": "test456",
        "condition": "RetentionEndDate"
    }       
}

如何使这个规则标签动态化?我的意思是如何解析这个"RULE_1""RULE_2" 标签?因为标签应该是不变的,我相信。如何实现上述格式?

【问题讨论】:

    标签: json typescript typescript-typings mapped-types


    【解决方案1】:

    您可以使用 typescript Record 内置类型。你在后台使用index types and mapped types的原理。

    但您真正需要知道的只是:Record<string, Rules> 定义了一个对象,其键是字符串,值是 Rules 的实例。

    你的 JSON 对象可以用

    来描述
    interface HasRetentionRules {
      dataRetentionRules: Record<string, Rules>
    }
    

    请注意,这是断言 any 字符串键对应于 Rules 对象并且它不检查无效键,因此您需要自己检查无效键。或者,您可以使用Partial&lt;Record&lt;string, Rules&gt;&gt;,它表示任何字符串键的值都是Rulesundefined 类型的值。

    Typescript Playground Link

    【讨论】:

      猜你喜欢
      • 2016-11-06
      • 2015-10-11
      • 2011-05-16
      • 1970-01-01
      • 2020-05-08
      • 1970-01-01
      • 1970-01-01
      • 2013-03-18
      • 1970-01-01
      相关资源
      最近更新 更多