Lesson 5 of 20

Arrays & Tuples

Typed Arrays

In TypeScript, you can define the type of elements an array can hold. There are two syntaxes for declaring array types.

Example
// Array type syntax
let numbers: number[] = [1, 2, 3, 4, 5];
let names: string[] = ["Alice", "Bob"];

// Generic array syntax
let scores: Array<number> = [90, 85, 92];

// Mixed arrays with union types
let mixed: (string | number)[] = [1, "two", 3];

// Array methods are type-safe
numbers.push(6);     // OK
numbers.push("six"); // Error: string not assignable to number

Tuples

Tuples are fixed-length arrays where each element has a specific type. They're useful when you need to represent a pair or group of related values.

Example
// Tuple: fixed types at specific positions
let person: [string, number] = ["Alice", 25];

// Access elements
let name = person[0]; // string
let age = person[1];  // number

// Error: wrong order
let wrong: [string, number] = [25, "Alice"]; // Error!

// Optional tuple elements
let point: [number, number, number?] = [10, 20];

// Named tuples (for documentation)
type UserTuple = [name: string, age: number, active: boolean];
let user: UserTuple = ["Bob", 30, true];

Readonly Arrays & Tuples

You can make arrays and tuples immutable using the readonly modifier.

Example
// Readonly array
const colors: readonly string[] = ["red", "green", "blue"];
// colors.push("yellow"); // Error: push does not exist on readonly

// Readonly tuple
const point: readonly [number, number] = [10, 20];
// point[0] = 30; // Error: cannot assign to readonly

// ReadonlyArray utility type
const items: ReadonlyArray<string> = ["a", "b", "c"];