JSON到Typescript模型唯一键


{
"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;
}

我如何才能使一个独特的"键、值">添加标签时的模型?目前我无法发送除安卓和三星以外的密钥。

也许您可以使用一个标签数组?

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

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

let tags = new Set<Tag>()

您可以这样做

另请参阅TypeScript映射类型。

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

最新更新