Proper way to declare json object (typescript)
I have the following json file with data:
[{
"sectionKey": "key1",
"sectionName": "name",
"content": []
},
{
"sectionKey": "key2",
"sectionName": "name",
"content": []
}
]
My question is: how to declare the content of the array in typescript? like "Type"[]. Please do not suggest using any[] since it removes all type checking provided by TypeScript.
Solution 1:
interface CoolObject {
sectionKey: string;
sectionName: string;
content: Array<any>;
}
const greatArray: CoolObject[] = [
{
sectionKey: 'key1',
sectionName: 'name',
content: [],
},
{
sectionKey: 'key2',
sectionName: 'name',
content: [],
foobar: 'something' // not assignable to type 'CoolObject'
},
];
If it's the 'content' poperty you're trying to typehint you can use Array<YourType>
or YourType[]
too.