0

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?

3 Answers 3

1

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);
Sign up to request clarification or add additional context in comments.

Comments

1

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); 

Comments

0

You should use Object or any instead:

var arr: Array<any>;

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.