【发布时间】:2019-11-15 07:41:08
【问题描述】:
为了类型安全,我想将以下 json 对象转换为 Typescript 接口:
{
"attributes1": {
"myKey1": {
"myinnerKey11": {
"value": "value 1",
"name": "name 1"
},
"myinnerKey12": {
"value": "value 1",
"name": "name 1",
"otherKey": "key 2"
}
}
},
"attributes2": {
"myKey2": {
"myinnerKey21": {
"value": "value 1",
"name": "name 1"
},
"myinnerKey22": {
"value": "value 1",
"name": "name 1",
"otherKey": "key 2"
}
}
}
}
我尝试创建以下界面:
export interface IFinalObj {
attributes1: IAttributes1;
attributes2: IAttributes2;
}
interface IMyInnerObj {
value: string;
name: string;
otherKey?: string;
}
interface IDynamicInnerKey {
[a: string]: IMyInnerObj
}
interface IAttributes1 {
myKey1: IDynamicInnerKey;
}
interface IAttributes2 {
myKey2: IDynamicInnerKey;
}
我不确定在更改 Keys 值并添加新对象时该怎么办
【问题讨论】:
-
在你的情况下,“期望的输出”是什么?
-
使用这个为您生成界面的工具怎么样? json2ts.com 。此外,“但它没有返回所需的输出并且代码看起来很乱”是什么意思。接口什么都不返回,它们只是签名,在运行时,它们什么都不做。
-
这取决于哪些属性是固定的,哪些是动态的,然后你可以为你的类做更好的类型。
-
@Atomzwieback 因为这是一个模型,所以像“attributes2”和“attributes1”这样的键正在改变,因为它可能像“abc”、“foo”这样的东西,所以当我映射到我的模型时它会中断跨度>
标签: json angular typescript