[英]Convert Dictionary JSON to Typescript model
I want to convert following json object to Typescript Interface for type safety :为了类型安全,我想将以下 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"
}
}
}
}
i tried creating the following interface :我尝试创建以下界面:
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;
}
I'm not sure what to do when the Keys value will be changed and new objects get added我不确定当 Keys 值将被更改并添加新对象时该怎么办
It seems like you need the Record<T1, T2> interface but if you're looking to generate typings from data, then yes, http://json2ts.com/ is the best tool.看起来您需要Record<T1, T2>接口,但如果您希望从数据生成类型,那么是的, http://json2ts.com/是最好的工具。
I wrote a poor version of that and tested with your model:我写了一个糟糕的版本并用你的模型进行了测试:
interface ITest {
attributes1: {
myKey1: {
myinnerKey11: {
value: string,
name: string
},
myinnerKey12: {
value: string,
name: string,
otherKey: string
}
}
},
attributes2: {
myKey2: {
myinnerKey21: {
value: string,
name: string
},
myinnerKey22: {
value: string,
name: string,
otherKey: string
}
}
}
}
You can try it here https://json2dts.stackblitz.io/ and the source code is at https://stackblitz.com/edit/json2dts .您可以在此处尝试https://json2dts.stackblitz.io/ ,源代码位于https://stackblitz.com/edit/json2dts 。
As you can see, it is very simplistic and does not try to pattern match at all.如您所见,它非常简单,根本不尝试模式匹配。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.