0Pricing
TypeScript Academy · Lesson

readonly Arrays and Tuples

Lock arrays and tuples against mutation methods.

Readonly Arrays

A readonly array is an array you can read from but not modify. Write it as readonly number[] or equivalently ReadonlyArray<number>. The element type stays the same; only mutation is blocked.

const nums: readonly number[] = [1, 2, 3];
console.log(nums[0], nums.length);
// nums[0] = 9; // Error: index signature is readonly

The ReadonlyArray Type

ReadonlyArray<T> is the generic form, identical in meaning to readonly T[]. Use whichever reads better; they're interchangeable.

const names: ReadonlyArray<string> = ['Ada', 'Sam'];
console.log(names.join(', '));

All lessons in this course

  1. readonly Properties
  2. readonly Arrays and Tuples
  3. ReadonlyArray and ReadonlyMap
  4. Deep Immutability Patterns
← Back to TypeScript Academy