Readonly with Arrays and Tuples
What you'll learn: How applying Readonly<T> to arrays and tuples creates immutable collections at compile-time.
The Core Idea
When you use Readonly<T> on an array type, TypeScript prevents you from modifying the array through methods like push, pop, or direct index assignment. This creates a readonly array.
TypeScript also gives you two equivalent syntaxes:
ReadonlyArray<T>(the generic form)readonly T[](the shorthand)
Both mean exactly the same thing — they're just different ways to write it.
How It Works
const numbers: Readonly<number[]> = [1, 2, 3];
// ❌ Error: Property 'push' does not exist
numbers.push(4);
// ❌ Error: Index signature is readonly
numbers[0] = 99;
// ✅ Reading is fine
console.log(numbers[1]); // 2
You can also use the shorthand:
const names: readonly string[] = ["Alice", "Bob"];
// Same compile-time protection
Or the ReadonlyArray generic:
const items: ReadonlyArray<string> = ["x", "y"];
// Identical behavior
With Tuples
Readonly works beautifully with tuples too:
const point: Readonly<[number, number]> = [10, 20];
// ❌ Cannot modify
point[0] = 5;
// Or use the shorthand
const color: readonly [number, number, number] = [255, 0, 128];
Why This Matters
Think of readonly arrays like library books: you can read them, pass them around, but you can't tear out pages or add new ones. This prevents accidental mutations in functions that only need to read data, not change it.
Key Takeaway: Readonly<T[]>, readonly T[], and ReadonlyArray<T> are three equivalent ways to create compile-time immutable arrays; the same pattern applies to tuples for fixed-length readonly collections.