JavaScript type script Property 0 is missing in type []

Viewed 12974

I want to have an array of an object as follows.

However typescript throws up an error Property 0 is missing in type []

let organisations: [{name: string, collapsed: boolean}] = [];
2 Answers

What you are defining is a tuple type (an array with a fixed number of elements and heterogeneous types). Since tuples have a fixed number of elements the compiler checks the number of elements on assignment.

To define an array the [] must come after the element type

let organisations: {name: string, collapsed: boolean}[] = [];

Or equivalently we can use Array<T>

let organisations: Array<{name: string, collapsed: boolean}> = [];

You can define tuples types like -

type organisationsType = {name: string, collapsed: boolean};
let organisations: organisationsType[];

Remember array the [] must come after the element type, like organisationsType in above example.

Related