Readonly Arrays and Tuples
What you'll learn: How to prevent accidental array mutations using TypeScript's readonly modifier and ReadonlyArray<T> type.
The Problem: Arrays Are Mutable by Default
In JavaScript (and TypeScript), arrays are mutable—you can push, pop, splice, and modify them freely. This is often fine, but sometimes you want to guarantee that a function can't change an array you pass to it, or that a class property stays constant.
Making Arrays Readonly
TypeScript gives you two equivalent ways to declare readonly arrays:
const numbers: readonly number[] = [1, 2, 3];
// or
const numbers: ReadonlyArray<number> = [1, 2, 3];
With either syntax, TypeScript prevents mutating operations:
const scores: readonly number[] = [100, 95, 88];
scores[0] = 99; // ❌ Error: Index signature is readonly
scores.push(92); // ❌ Error: Property 'push' does not exist
scores.pop(); // ❌ Error: Property 'pop' does not exist
You can still read values and use non-mutating methods like map, filter, and slice—these return new arrays without changing the original.
Readonly Tuples
The same readonly modifier works with tuples:
const point: readonly [number, number] = [10, 20];
point[0] = 15; // ❌ Error: Cannot assign to readonly index
This is especially useful when you want to ensure coordinate pairs, configuration values, or other fixed-length structures remain unchanged.
Why This Matters
Think of readonly like a protective seal on a package. You're telling TypeScript: "This data should not be modified here." It prevents bugs where functions unexpectedly alter shared data, and makes your intentions clear to other developers (and future you).
Key Takeaway: Use readonly T[] or ReadonlyArray<T> to prevent array mutations at compile time, ensuring data stays unchanged when you need immutability guarantees.