Skip to content

TypeScript - Arrays

Arrays are fundamental data structures used to store ordered collections of items. In TypeScript, arrays are designed to hold items of the same type, providing type safety for array operations.

Compared to individual variables, arrays allow you to efficiently store and manage multiple related values under a single name.

There are two primary syntaxes for declaring array types in TypeScript:

  1. Type followed by []: elementType[] (e.g., number[], string[]) - This is the most common syntax.
  2. Generic Array Type: Array<elementType> (e.g., Array<number>, Array<string>) - Useful in some complex type scenarios.

Initialization typically uses array literal syntax [...].

// Using type[] syntax
let scores: number[] = [70, 85, 92, 68];
let names: string[] = ["Alice", "Bob", "Charlie"];
// Using Array<type> syntax
let flags: Array<boolean> = [true, false, true];
// Declaring an empty array (explicit type needed)
let results: number[] = [];
// Initialization after declaration
let cities: string[];
cities = ["London", "Paris", "Tokyo"];
// Type inference also works
const inferredNumbers = [10, 20, 30]; // TypeScript infers number[]
// inferredNumbers.push("40"); // Error: Argument of type 'string' is not assignable to parameter of type 'number'.

Array elements are accessed using zero-based numerical indices inside square brackets [].

let fruits: string[] = ["Apple", "Banana", "Orange"];
console.log(fruits[0]); // Output: Apple
console.log(fruits[1]); // Output: Banana
// Modifying an element
fruits[1] = "Blueberry";
console.log(fruits[1]); // Output: Blueberry
// Accessing the length (number of elements)
console.log(`Number of fruits: ${fruits.length}`); // Output: 3

Several ways exist to loop through array elements:

Iterates directly over the values of the array.

const colors: string[] = ["Red", "Green", "Blue"];
console.log("\nUsing for...of:");
for (const color of colors) {
console.log(color.toUpperCase());
}

Executes a provided callback function once for each array element.

console.log("\nUsing forEach:");
colors.forEach((color, index) => {
console.log(`Color at index ${index}: ${color}`);
});

Useful when you need access to the index within the loop body.

console.log("\nUsing standard for loop:");
for (let i = 0; i < colors.length; i++) {
console.log(`Index ${i}, Color ${colors[i]}`);
}

4. for...in Loop (Generally Avoid for Arrays)

Section titled “4. for...in Loop (Generally Avoid for Arrays)”

Iterates over the keys (indices as strings) of the array, including potentially inherited properties. It’s generally not recommended for array iteration; use for...of or forEach instead.

console.log("\nUsing for...in (indices are strings):");
for (const index in colors) {
// index will be "0", "1", "2"
console.log(`Index: ${index}, Type: ${typeof index}, Value: ${colors[index]}`);
}

Arrays come with many built-in methods for manipulation (most inherited from JavaScript):

MethodDescription
push(item1, ...)Adds one or more elements to the end of the array (mutates original).
pop()Removes and returns the last element (mutates original).
shift()Removes and returns the first element (mutates original).
unshift(item1, ...)Adds one or more elements to the beginning (mutates original).
slice(start?, end?)Returns a shallow copy of a portion of the array into a new array (does not mutate).
splice(start, deleteCount?, item1?, ...)Changes the contents by removing or replacing existing elements and/or adding new ones (mutates original).
concat(arr1, ...)Returns a new array by merging this array with other arrays/values (does not mutate).
join(separator?)Joins all elements into a string, separated by separator (default is ’,’).
indexOf(item, fromIndex?)Returns the first index at which item can be found, or -1.
lastIndexOf(item, fromIndex?)Returns the last index at which item can be found, or -1.
includes(item, fromIndex?)Returns true if the array contains item, false otherwise.
map(callbackFn)Creates a new array populated with the results of calling callbackFn on every element.
filter(callbackFn)Creates a new array with all elements that pass the test implemented by callbackFn.
reduce(callbackFn, initialValue?)Executes a reducer function on each element, resulting in a single output value.
reduceRight(...)Similar to reduce, but processes from right-to-left.
some(callbackFn)Tests whether at least one element passes the test implemented by callbackFn.
every(callbackFn)Tests whether all elements pass the test implemented by callbackFn.
sort(compareFn?)Sorts the elements in place (mutates original). Optional compareFn defines sort order.
reverse()Reverses the order of elements in place (mutates original).

Easily unpack values from arrays into distinct variables.

const coordinates: number[] = [10, 20, 30];
// Basic destructuring
const [x, y, z] = coordinates;
console.log(`x=${x}, y=${y}, z=${z}`); // Output: x=10, y=20, z=30
// Destructuring with rest element
const [first, ...rest] = coordinates;
console.log(`First: ${first}`); // Output: First: 10
console.log(`Rest: ${rest}`); // Output: Rest: [20, 30]
// Skipping elements
const [, second, ] = coordinates;
console.log(`Second: ${second}`); // Output: Second: 20

TypeScript allows you to create immutable arrays using ReadonlyArray<Type> or readonly Type[]. These arrays cannot be modified after creation.

const immutableNums: ReadonlyArray<number> = [1, 2, 3];
const readonlyStrings: readonly string[] = ["a", "b"];
// immutableNums[0] = 10; // Error: Index signature in type 'readonly number[]' only permits reading.
// immutableNums.push(4); // Error: Property 'push' does not exist on type 'readonly number[]'.
// Can still read elements
console.log(immutableNums[0]); // Output: 1

Arrays can contain other arrays, creating multi-dimensional structures (like matrices or grids).

let matrix: number[][] = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
];
console.log(matrix[0][1]); // Output: 2 (Row 0, Column 1)
console.log(matrix[2][0]); // Output: 7 (Row 2, Column 0)