Tân
Tân

Reputation: 1

Array<object> in typescript

I wanna add an object to an array but I don't know how to declare a variable with the return type is Array<object>.

My example:

var obj = {
   'Prop name': 'Prop value'
};

document.body.innerHTML = typeof obj; // output: object

var arr: Array<object>; // error message: Cannot find name 'object'
arr.push(obj);

I've tried again with:

var obj: Object = {
   'Prop name': 'Prop value'
};

document.body.innerHTML = typeof obj; // output: object

var arr: Array<Object>;
arr.push(obj); // error message: Cannot read property 'push' of undefined

How can I fix the issue?

Upvotes: 0

Views: 1028

Answers (3)

MartyIX
MartyIX

Reputation: 28648

You miss initialization of arr array:

var obj: Object = {
   'Prop name': 'Prop value'
};

document.body.innerHTML = typeof obj; // output: object

var arr: Array<Object> = []; // MODIFIED
arr.push(obj); 

Upvotes: 1

vzayko
vzayko

Reputation: 335

You should use Object or any instead:

var arr: Array<any>;

Upvotes: 0

Richard Szalay
Richard Szalay

Reputation: 84734

The first error is because it's Object (title case) not object (lower case)

The second error is because you've typed the variable, but not actually assigned an instance. Try:

var arr: Array<Object> = [];
arr.push(obj);

Upvotes: 1

Related Questions