我是一名Java开发人员,我现在想开发Angular 6.0,我对打字稿很陌生。 现在我有一个来自后端的 json 字符串,如下所示:
{
"test1":{
"aa":"7/22 – 7/28",
"bb":"Tues July 24 11:15 - 22:20"
},
"test2":{
"aa":"7/22 – 7/28",
"bb":"Tues July 24 11:15 - 22:20"
}
}
如何声明类对象?
从Java的角度来看,我将像这样声明该类,我不确定它是否正确
export class Test{
public aa: string;
public bb: string;
}
export class Main{
public test1: Test;
public test2: Test;
}
试试这个:
class test {
aa: string;
bb: string;
}
class root {
[key: string] : test;
}
const t: root = {
'test2': { aa: 'hello', bb: 'world'},
'test1': { aa: 'hello', bb: 'world'}
}
这也通过在编译时发现重复键时引发错误来提供安全性,即:
const t: root = {
'test2': { aa: 'hello', bb: 'world'},
'test1': { aa: 'hello', bb: 'world'},
'test1': { aa: 'hello', bb: 'world'}
}
显示:
重复的标识符"test1"。
但是,这可能不适合您展示的 POJO。
在这里尝试一下 TS游乐场
不,它应该是这样的,
export interface Test1 {
aa: string;
bb: string;
}
export interface Test2 {
aa: string;
bb: string;
}
为了验证,您只需将JSON粘贴到json2ts
中即可查看输出。