【问题标题】:JSON to Typescript Model Unique keyJSON 到 Typescript 模型唯一键
【发布时间】:2021-05-24 10:02:54
【问题描述】:
{
    "title" : "Samsung Galaxy S10",
    "tags" : {
     "android" : true,
     "samsung" : true
    }   
}

我正在使用 Typescript 对 JSON 输出进行建模,如下所示。

export interface PostModel {
    title: string;
    tags:  Tags;
}

export interface Tags {
    android: boolean;
    samsung: boolean;
}

如何在添加标签时制作唯一的“键、值”模型?目前我无法发送除 android 和 samsung 以外的密钥。

【问题讨论】:

    标签: javascript json typescript react-typescript


    【解决方案1】:

    也许你可以使用一组标签?

    export interface PostModel {
        title: string;
        tags:  Tag[];
    }
    
    export interface Tag {
        key: string;
        value: boolean;
    }
    

    不确定 typescript 是否有办法检查所有标签是否唯一,也许您可​​以将 tags 设为 new Set(),这样所有值只会出现一次

    let tags = new Set<Tag>()
    

    【讨论】:

      【解决方案2】:

      你可以这样做,

      另请参考TypeScript Mapped Types

      export interface UniqueModel {
        [key: string]: any
      }
      
      const tags: Tags[] = [];
      const obj1: UniqueModel = { tags };
      

      【讨论】:

        猜你喜欢
        • 2018-07-06
        • 2011-11-15
        • 1970-01-01
        • 1970-01-01
        • 2012-04-23
        • 2015-06-15
        • 2023-03-26
        • 2021-01-26
        • 2020-02-05
        相关资源
        最近更新 更多