stevenpcurtis
stevenpcurtis

Reputation: 2001

JavaScript type script Property 0 is missing in type []

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}] = [];

Upvotes: 24

Views: 13153

Answers (2)

Praveen Poonia
Praveen Poonia

Reputation: 765

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.

Upvotes: 1

Titian Cernicova-Dragomir
Titian Cernicova-Dragomir

Reputation: 249706

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}> = [];

Upvotes: 44

Related Questions