Advertisement
Beginner TypeScript, Readonly, const Assertions & Immutability

How do you make an entire array type read-only, preventing both element mutation and array-mutating methods?

Short answer

Prefix the array type with 'readonly', or use the generic `ReadonlyArray ` — both prevent index assignment AND remove access to mutating methods like push, pop, splice, and sort from the type entirely.

Save TypeScript mock interview
Advertisement
AModel answer
Prefix the array type with 'readonly', or use the generic `ReadonlyArray<T>` — both prevent index assignment AND remove access to mutating methods like push, pop, splice, and sort from the type entirely.
const nums: readonly number[] = [1, 2, 3];
// nums.push(4); // Error: 'push' does not exist on type 'readonly number[]'
// nums[0] = 99;  // Error: index signature is read-only
Real-world example
Typing a function parameter that should be able to read a caller's array but must never accidentally mutate it.
Likely follow-ups
  • Which specific array methods remain available on a readonly array type, versus which are removed?
Related topics