typescript-arrays

Using Arrays in TypeScript

  • 4 min

In TypeScript, an Array is an ordered collection of elements, which can be of any type (although they are generally homogeneous).

TypeScript provides several ways to declare and manipulate arrays, making handling collections of data quite comfortable and straightforward.

If you want to learn more, check out the Introduction to Programming Course

There are two main syntaxes for declaring an array in TypeScript. The most common one uses brackets ([]), as follows.

let numeros: number[] = [1, 2, 3, 4, 5];
let palabras: string[] = ["TypeScript", "JavaScript", "Node.js"];
Copied!

Alternatively, we can use the Generic Class Array<T>

let numeros: Array<number> = [1, 2, 3, 4, 5];
let palabras: Array<string> = ["TypeScript", "JavaScript", "Node.js"];
Copied!

Generally, we will use the first one, except in some advanced cases (such as factories) where we will need to use the second one.

Iterating over arrays

TypeScript supports iteration using traditional loops and the for...of syntax.

for (let i = 0; i < numeros.length; i++) {
    console.log(numeros[i]);
}

for (let num of numeros) {
    console.log(num);
}
Copied!

Additionally, we have the forEach method, which is an Array method that serves the same purpose (we will see it in the next section).

Array methods and properties

TypeScript inherits array methods and properties from JavaScript, so we have a large number of functions available to manipulate and operate on arrays.

Practical examples