Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading