Readonly Arrays
What you'll learn: How to prevent accidental mutations on arrays using TypeScript's readonly array types.
The Problem with Regular Arrays
By default, TypeScript arrays are mutable—you can push, pop, splice, or modify them at any time. This flexibility is useful, but sometimes you want to guarantee an array won't change after creation. That's where readonly arrays come in.
What is a Readonly Array?
A readonly array is an array type that TypeScript treats as immutable. You can read from it (access elements, iterate, use methods like filter or map), but you cannot modify it (no push, pop, splice, or index assignment).
TypeScript gives you two ways to declare readonly arrays:
const numbers: ReadonlyArray<number> = [1, 2, 3];
const names: readonly string[] = ["Alice", "Bob"];
Both syntaxes mean the same thing—the array cannot be mutated.
What You Cannot Do
const scores: readonly number[] = [10, 20, 30];
scores.push(40); // ❌ Error: Property 'push' does not exist
scores[0] = 99; // ❌ Error: Index signature is readonly
TypeScript blocks any operation that would change the array.
What You Can Still Do
const scores: readonly number[] = [10, 20, 30];
console.log(scores[0]); // ✅ 10
const doubled = scores.map(x => x * 2); // ✅ Returns new array
Reading values and using non-mutating array methods still works perfectly.
Why Use Readonly Arrays?
Think of a readonly array like a locked display case: you can look at the items inside, but you can't add, remove, or rearrange them. This prevents bugs from accidental modifications and makes your intent clear to other developers.
Key Takeaway: Use ReadonlyArray<T> or readonly T[] when you want to guarantee an array won't be modified, preventing mutation bugs while still allowing safe read operations.