TExcelTAD
Home › TypeScript › TS Readonly & Immutability

TypeScript Readonly & Immutability

Many bugs come from data changing when you didn't expect it: a function that "just reads" an array quietly sorts it in place, or a configuration object gets overwritten halfway through a program. TypeScript gives you several tools to mark data as read-only, so the compiler refuses any code that tries to change it.

All of these checks happen at compile time only. The JavaScript that runs is unchanged — readonly disappears during compilation, just like every other type annotation.

Readonly properties

Put readonly in front of a property in an interface, type alias or class. The property can be set when the object is created, but never assigned again:

ts · try it yourself
interface Point {
  readonly x: number;
  readonly y: number;
}

const p: Point = { x: 3, y: 4 };
p.x = 10;
console.log(p);
main.ts(7,3): error TS2540: Cannot assign to 'x' because it is a read-only property.

Instead of changing the point, create a new one. The spread operator makes this easy:

ts · try it yourself
interface Point {
  readonly x: number;
  readonly y: number;
}

const p: Point = { x: 3, y: 4 };
const moved: Point = { ...p, x: 10 };
console.log(p, moved);
{ x: 3, y: 4 } { x: 10, y: 4 }

In classes, a readonly field may be assigned in its declaration or in the constructor, and nowhere else:

ts · try it yourself
class Account {
  readonly id: string;
  balance = 0;

  constructor(id: string) {
    this.id = id;          // allowed: inside the constructor
  }

  deposit(amount: number) {
    this.balance += amount; // fine: balance is not readonly
  }
}

const acc = new Account("AC-17");
acc.deposit(50);
console.log(acc.id, acc.balance);
AC-17 50

Readonly arrays

readonly string[] (or the long form ReadonlyArray<string>) is an array type without the mutating methods — push, pop, splice, sort, reverse and index assignment are all gone. Non-mutating methods such as map, filter, slice and toSorted still work:

ts · try it yourself
function topScores(scores: readonly number[]): number[] {
  scores.sort((a: number, b: number) => b - a);
  return scores.slice(0, 2);
}
main.ts(2,10): error TS2339: Property 'sort' does not exist on type 'readonly number[]'.

The fix is to sort a copy. toSorted() (ES2023) returns a new array and leaves the original alone:

ts · try it yourself
function topScores(scores: readonly number[]): number[] {
  return scores.toSorted((a, b) => b - a).slice(0, 2);
}

const results = [72, 95, 88, 61];
console.log(topScores(results));
console.log(results); // unchanged
[ 95, 88 ]
[ 72, 95, 88, 61 ]

Tip: Use readonly array parameters whenever a function only reads its input. Callers can then pass both normal and readonly arrays, and they know you won't modify their data.

The Readonly<T> utility type

Readonly<T> makes every property of T read-only in one go. It is handy for state objects and configuration:

Tool Effect
readonly prop: T one property can't be reassigned
readonly T[] / ReadonlyArray<T> array without mutating methods
Readonly<T> all top-level properties of T become readonly
ReadonlyMap<K, V> / ReadonlySet<T> map/set without set, add, delete, clear
as const deep readonly + literal types for a value

Readonly<T> is shallow: nested objects are still mutable unless they are also marked.

as const: deeply readonly values

Adding as const after a literal tells TypeScript to infer the narrowest, read-only type: every property becomes readonly, arrays become readonly tuples, and strings and numbers keep their literal values.

ts · try it yourself
const settings = {
  theme: "dark",
  sizes: [12, 14, 16],
} as const;

// type: { readonly theme: "dark"; readonly sizes: readonly [12, 14, 16] }
type Size = (typeof settings.sizes)[number];

const s: Size = 14;
console.log(settings.theme, s, settings.sizes.length);
dark 14 3

Readonly is a compile-time promise

Remember that readonly does not freeze anything at runtime. If you need a runtime guarantee too, combine it with Object.freeze, whose return type is already Readonly<T>:

ts · try it yourself
const limits = Object.freeze({ maxUsers: 5, maxFiles: 20 });

try {
  (limits as { maxUsers: number }).maxUsers = 99;
} catch (err) {
  console.log((err as Error).message);
}
console.log(limits.maxUsers);
Cannot assign to read only property 'maxUsers' of object '#<Object>'
5

The cast silences the compiler, but because modules run in strict mode, assigning to a frozen property throws a TypeError.

Test yourself

Which method is NOT available on a readonly number[]?

  1. map
  2. slice
  3. push
  4. toSorted

Where can a class's readonly field be assigned?

  1. Anywhere inside the class
  2. Only in its declaration or the constructor
  3. Only in static methods
  4. Nowhere — it must stay undefined

What does Readonly<T> do at runtime?

  1. Freezes the object
  2. Throws on assignment
  3. Nothing — it only exists at compile time
  4. Copies the object