Reputation: 103
I'm a java developer, I want to develop the Angular 6.0 now, I'm pretty new on the typescript. now I have a json string from the backend as below:
{
"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"
}
}
How to declare the class Object?
for the java perspective, I will declare the class like this, I'm not sure whether it's right or not
export class Test{
public aa: string;
public bb: string;
}
export class Main{
public test1: Test;
public test2: Test;
}
Upvotes: 0
Views: 41
Reputation: 13248
try this:
class test {
aa: string;
bb: string;
}
class root {
[key: string] : test;
}
const t: root = {
'test2': { aa: 'hello', bb: 'world'},
'test1': { aa: 'hello', bb: 'world'}
}
This also provides safety by raising an error at compile time when duplicate keys are found ie:
const t: root = {
'test2': { aa: 'hello', bb: 'world'},
'test1': { aa: 'hello', bb: 'world'},
'test1': { aa: 'hello', bb: 'world'}
}
shows:
Duplicate identifier ''test1''.
However, this may not fit in with your POJO's that you have shown.
Try it here TS Playground
Upvotes: 1
Reputation: 222582
No, it should look something like this,
export interface Test1 {
aa: string;
bb: string;
}
export interface Test2 {
aa: string;
bb: string;
}
in order to verify you can just paste the JSON in json2ts
and see the output.
Upvotes: 0