Shawn
Shawn

Reputation: 5260

typescript how to add new item to the beginning of an array

I used array.unshift() with my Angular2 project. And I got

TypeError: Cannot read property 'unshift' of undefined.

Typescript is a superset of JavaScript. Why array.unshift() is not recognized?

How can I add new item to the beginning of an array with Typescript?

Upvotes: 2

Views: 8404

Answers (3)

jorjun
jorjun

Reputation: 134

let fruits = ["Banana", "Cherry"]
fruits.unshift("Apple")

>["Apple", "Banana", "Cherry"]

Upvotes: 1

David Pine
David Pine

Reputation: 24525

The error message:

TypeError: Cannot read property 'unshift' of undefined.

Means that the "array" instance in context is actually undefined at the time of the execution of the invocation of the .unshift method. This error is raised when the method is attempted on an undefined variable. That is the root issue.

Once you correctly declare and instantiate the array, you should use slice.

Instead of:

let myArray;

Declare, and or instantiate:

let myArray: number[] = [];

Then you can add values and you could expect that at runtime array members would be available.

Rather that unshift, you are looking for the native array slice method. Since JavaScript is valid TypeScript, this is simple. Here is an example:

Upvotes: 3

awiseman
awiseman

Reputation: 5704

That error is saying that whichever identifier you are trying to invoke unshift() on actually has the value 'undefined' instead of array.

It's like if you were doing this:

var array = undefined;
array.unshift();

when you actually want this:

var array = [];
array.unshift();

double check that you are initializing your array correctly.

Upvotes: 6

Related Questions