Array in Typescript

In TypeScript, an array is a data structure that stores a collection of elements, which can be of any type, though typically of the same type. Arrays allow you to store multiple values in a single variable and access them via their index.

Creating Arrays in TypeScript

1. Array of a specific type:

You can define an array to contain elements of a specific type using the following syntax:


let numbers: number[] = [1, 2, 3, 4];
let strings: string[] = ["Apple", "Banana", "Orange"];

2. Using the Array generic type:

Another way to define an array is by using the Array<T> syntax, where T is the type of elements in the array:


let numbers: Array = [1, 2, 3, 4];
let strings: Array = ["Apple", "Banana", "Orange"];

Multi-dimensional Arrays

You can also create multi-dimensional arrays (arrays of arrays) in TypeScript:


let matrix: number[][] = [
  [1, 2, 3],
  [4, 5, 6],
  [7, 8, 9]
];

Array Methods

TypeScript arrays inherit many useful methods from JavaScript, such as:

push() – Adds elements to the end of the array.

pop() – Removes and returns the last element.

shift() – Removes and returns the first element.

unshift() – Adds elements to the beginning of the array.

map() – Creates a new array by applying a function to each element.

filter() – Creates a new array with all elements that pass a test.

reduce() – Reduces the array to a single value by applying a function.

Example:


let fruits: string[] = ["Apple", "Banana", "Orange"];
fruits.push("Mango");
console.log(fruits); // Output: ["Apple", "Banana", "Orange", "Mango"]