Advertisement
Advanced TypeScript, Primitive Types, Arrays & Tuples

How does readonly interact with tuple types, and what does `readonly [number, number]` prevent compared to a mutable tuple?

Short answer

A readonly tuple prevents any mutation of its elements after creation — no reassigning an index, and critically, none of the mutating array methods (push, pop, splice, sort) are even available on its type, since they'd violate the fixed-length, immutable contract; you can still…

Save TypeScript mock interview
Advertisement
AModel answer
A readonly tuple prevents any mutation of its elements after creation — no reassigning an index, and critically, none of the mutating array methods (push, pop, splice, sort) are even available on its type, since they'd violate the fixed-length, immutable contract; you can still read elements and destructure normally.
function getOrigin(): readonly [number, number] {
  return [0, 0];
}
const origin = getOrigin();
// origin[0] = 5; // Error: cannot assign to readonly tuple element
// origin.push(1); // Error: 'push' does not exist on type 'readonly [number, number]'
Real-world example
Returning an immutable coordinate pair or fixed-shape result from a function where callers shouldn't be able to mutate it.
Likely follow-ups
  • How does a readonly tuple type relate to the 'as const' assertion technique discussed earlier?
Related topics