'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?



Solution 1:[1]

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:

Solution 2:[2]

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

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

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2 jorjun