Readonly and immutability

Beginner · 5 min

Read-only arrays and tuples, `Readonly<T>`, and `as const`: how TypeScript stops mutation at compile time, and where that protection ends.

Before thisObject types, optional and readonly propertiesArrays and tuples

Jack Herrington · 5 min

Readonly and immutability

The player loads from youtube-nocookie.com when you press play. Nothing reaches YouTube before that.

Taught by Jack HerringtonReport a problem with this video
Not started
Set this lesson's status

What you'll learn

  • `const` stops a variable from being reassigned; it does nothing to stop the object or array it holds from being changed. Immutability of the value is what `readonly` types are for.
  • `readonly string[]` (or `ReadonlyArray<string>`) is an array type without `push`, `splice`, `sort`, or index assignment, so code holding it can read but not modify.
  • `Readonly<T>` marks every top-level property of `T` as `readonly` in one go; like the modifier itself, it is shallow.
  • `as const` makes a literal deeply read-only and keeps its narrowest literal types, so `["a", "b"] as const` is `readonly ["a", "b"]`.
  • A mutable array can be passed where a `readonly` one is expected, but not the reverse, so typing parameters as `readonly T[]` accepts every caller and promises not to mutate their data.
  • All of this is compile-time only; `Object.freeze` is the runtime counterpart, and it is shallow too.

The bug const doesn’t catch

Here is a classic way to corrupt shared state:

const DEFAULT_ROLES = ["viewer", "editor"];

function rolesFor(isAdmin: boolean) {
  const roles = DEFAULT_ROLES;
  if (isAdmin) roles.push("admin");
  return roles;
}

After one admin call, every user gets "admin", because roles and DEFAULT_ROLES are the same array. const didn’t help. It only stops the name DEFAULT_ROLES from being pointed at a different array; it says nothing about the array’s contents. (Reference semantics are a JavaScript topic, covered in the JavaScript roadmap.)

The previous lesson introduced readonly on single properties. This lesson extends it to whole arrays and objects, which is what the bug above needs.

Read-only arrays

Put readonly in front of an array type and the mutating methods disappear from it:

const DEFAULT_ROLES: readonly string[] = ["viewer", "editor"];

DEFAULT_ROLES.push("admin"); // Error: Property 'push' does not exist on type 'readonly string[]'.
DEFAULT_ROLES[0] = "owner"; // Error: Index signature in type 'readonly string[]' only permits reading.

const upper = DEFAULT_ROLES.map((r) => r.toUpperCase()); // fine, map returns a new array

ReadonlyArray<string> is the long form of the same type. Everything that reads (map, filter, includes, indexing) still works. Everything that writes in place (push, pop, splice, sort, reverse) is gone from the type. Non-mutating versions such as toSorted() remain, which is the point: they return a new array.

Tuples take the modifier the same way: readonly [string, number]. That closes the gap from the arrays and tuples lesson, where a plain tuple still allowed push.

Read-only parameters: a promise to callers

The most useful place for readonly is often a function parameter:

function average(values: readonly number[]) {
  let total = 0;
  for (const v of values) total += v;
  return total / values.length;
}

const scores = [80, 90]; // number[]
average(scores); // fine

A mutable number[] can be passed where readonly number[] is expected. The function only promised to read, and a mutable array can certainly be read. The reverse is refused:

function sortInPlace(values: number[]) {
  values.sort();
}

const fixed: readonly number[] = [3, 1, 2];
sortInPlace(fixed); // Error: Argument of type 'readonly number[]' is not assignable to parameter of type 'number[]'.

Think of it like lending a document. Handing out the original to someone who promises only to read it is safe. Handing a “do not edit” copy to someone whose job description includes editing is not. So typing parameters readonly costs callers nothing and makes a real promise about their data.

Readonly<T> for whole objects

Writing readonly before every property is repetitive. Readonly<T> does it for all top-level properties at once:

type Settings = {
  theme: string;
  fontSize: number;
  shortcuts: string[];
};

function render(s: Readonly<Settings>) {
  s.theme = "dark"; // Error: Cannot assign to 'theme' because it is a read-only property.
  s.shortcuts.push("ctrl+k"); // compiles: Readonly<T> is shallow
}

Readonly<T> is a utility type, built from a mapped type; the object utility types lesson shows how it is made. What matters here is its reach: one level. The shortcuts array is still a mutable string[]. For deep protection, nested types need their own readonly, which in practice means declaring shortcuts: readonly string[] in the type itself.

as const: read-only all the way down

For values written out as literals, such as configuration, lookup tables, or lists of options, as const is the shortcut:

const config = {
  theme: "dark",
  sizes: [12, 14, 16],
} as const;
// { readonly theme: "dark"; readonly sizes: readonly [12, 14, 16] }

config.theme = "light"; // Error: Cannot assign to 'theme' because it is a read-only property.
config.sizes.push(18); // Error: Property 'push' does not exist on type 'readonly [12, 14, 16]'.

It does two things at once. Every level becomes read-only, and every value keeps its literal type, so theme is "dark", not string. That second effect is why as const shows up so often in the union and literal types and enums lessons. It only works on literal expressions; you can’t apply it to a variable that already exists.

Compile time, not runtime

Every form of readonly here is erased. Nothing stops plain JavaScript, or a value cast to another type, from mutating the data. Object.freeze is the runtime equivalent, and TypeScript understands it: the type it returns from Object.freeze({ a: 1 }) is Readonly<{ a: 1 }>. It is also shallow. For most application code, the compile-time check is all you need, and it is free.

About the video

Jack Herrington’s short video covers this lesson’s ground in about five minutes: read-only fields, Readonly<T>, read-only arrays and tuples, and as const for values that should never change. It dates from 2021, and every feature it shows behaves the same in TypeScript 5. The video moves fast; the sections above slow down on two things it passes quickly: why mutable arrays are assignable to read-only parameters but not the reverse, and that Readonly<T> stops at the first level. Matt Pocock’s video in the links is a focused look at as const.

Check yourself

  1. 01Why does `const items = [1, 2]; items.push(3);` compile?

    `const` only prevents assigning a new value to the `items` binding. The array itself is still a normal mutable `number[]`, and `push` changes the array, not the binding. To prevent that, the array needs a read-only type such as `readonly number[]`.

  2. 02Why is a `readonly string[]` not assignable to a `string[]` parameter?

    The function receiving a `string[]` is allowed to call `push` or `sort` on it. Passing a read-only array there would let the function mutate data that was promised to be read-only, so the compiler refuses. The opposite direction is safe, because a function that only reads cannot misuse a mutable array.

  3. 03What is the difference between `Readonly<Settings>` and `settings as const`?

    `Readonly<Settings>` is a type you annotate with; it marks the top-level properties `readonly` and keeps their declared types. `as const` is applied to a literal value; it makes every level read-only and infers literal types such as `"dark"` instead of `string`.

  4. 04Does marking a type `readonly` make `Object.freeze` unnecessary?

    They cover different things. `readonly` stops your typed code from compiling a mutation, at no runtime cost. `Object.freeze` stops mutation at runtime, including from untyped code, but only one level deep. Most code needs only the type-level guarantee.

Go deeper

Notes

Private to you

Esc
↑↓ navigate↵ open? shortcuts

Keyboard shortcuts

Press Esc to close

Anywhere

⌘K
Search and commands
/
Search
?
This sheet
Esc
Close

Reading a lesson

J
Next lesson
K
Previous lesson
B
Bookmark