Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript type script Property 0 is missing in type []

Tags:

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}] = []; 
like image 304
stevenpcurtis Avatar asked Sep 17 '18 07:09

stevenpcurtis


People also ask

Is missing in type TypeScript?

The TypeScript error "Property is missing in type but required in type" occurs when we do not set all of the properties an object of the specified type requires. To solve the error, make sure to set all of the required properties on the object or mark the properties as optional.

Is missing the following properties from type?

The error "Type is missing the following properties from type" occurs when the type we assign to a variable is missing some of the properties the actual type of the variable expects. To solve the error, make sure to specify all of the required properties on the object.

Does not exist on type?

The "Property does not exist on type '{}'" error occurs when we try to access or set a property that is not contained in the object's type. To solve the error, type the object properties explicitly or use a type with variable key names.

What is TypeScript never?

TypeScript introduced a new type never , which indicates the values that will never occur. The never type is used when you are sure that something is never going to occur. For example, you write a function which will not return to its end point or always throws an exception.


1 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}> = []; 
like image 73
Titian Cernicova-Dragomir Avatar answered Sep 20 '22 05:09

Titian Cernicova-Dragomir