Readonly Arrays and Tuples

Prevent an array from being modified after it is created.

Syntaxlet list: readonly number[] = [1, 2, 3];

Mark an array as readonly to stop code from adding, removing, or changing elements. Methods like push and pop become unavailable, protecting your data from accidental mutation.

This is useful for constants and for values you pass around that should never change.

Example

Try it yourself
Loading editor…
Press Run to execute the code.

When to use it

  • A configuration module exports a readonly string[] of allowed domains so no module can modify the list at runtime.
  • A pure function accepts ReadonlyArray<number> to signal it will not mutate the caller's data.
  • A Redux-style state object uses readonly tuples so reducers cannot accidentally mutate state in place.

More examples

ReadonlyArray prevents mutation

Shows that ReadonlyArray blocks both push and index-based mutation while still allowing read access.

Example · ts
const allowed: ReadonlyArray<string> = ['admin', 'editor', 'viewer'];

allowed.push('guest');    // Error: Property 'push' does not exist on type 'readonly string[]'
allowed[0] = 'superuser'; // Error: Index signature in type 'readonly string[]' only permits reading

readonly array shorthand

Uses the readonly T[] shorthand and demonstrates that spreading to a new array is the correct way to derive a modified copy.

Example · ts
const scores: readonly number[] = [95, 87, 72];

// Read operations work fine
const top = scores[0];
const copy = [...scores, 100]; // spread to a new array is fine

// scores.sort(); // Error: sort mutates in place

Readonly tuple

Declares a readonly tuple type for a 2D coordinate and shows the compile error when attempting to reassign a position.

Example · ts
type Coordinate = readonly [number, number];

const origin: Coordinate = [0, 0];
origin[0] = 1; // Error: Cannot assign to '0' because it is a read-only property

function distance([x, y]: Coordinate): number {
  return Math.sqrt(x * x + y * y);
}

Discussion

  • Be the first to comment on this lesson.