Skip to content
Tutorials Center
My learning

Topics

Lesson 35 of 96 ยท Objects and Classes

Readonly and Immutability

Learn immutability in TypeScript - readonly properties, Readonly<T>, readonly arrays, ReadonlyMap and ReadonlySet, as const, deep readonly types, Object.freeze and safe updates.

Many bugs come from data changing when you didn't expect it to: a function that sorts the array you passed in, a "default settings" object that one module quietly edits for everyone, a shared list that grows while you loop over it. Immutability means treating data as fixed once it's created, and producing new values instead of editing old ones.

TypeScript gives you compile-time tools for this: the readonly modifier, the Readonly<T> utility type, read-only array, Map and Set types, and as const. They cost nothing at runtime, because they're erased like all types. This lesson shows each tool, where its protection ends (it's shallower than many people think), how it compares to JavaScript's runtime Object.freeze(), and the update patterns that make immutable code pleasant to write. It continues from Type Compatibility and Variance, where read-only arrays fixed an unsound assignment.

readonly properties

Put readonly in front of a property in an object type, interface or class, and TypeScript rejects any assignment to it after creation:

TypeScript readonly properties and class fields

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

A readonly class field can be assigned in its declaration or in the constructor, and nowhere else. Parameter properties work too: constructor(readonly id: string) {} declares and assigns the field in one step (see Classes).

Now try to break the rule:

TypeScript Assigning to readonly members (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

TEXT
main.ts(7,8): error TS2540: Cannot assign to 'x' because it is a read-only property.
main.ts(13,10): error TS2540: Cannot assign to 'id' because it is a read-only property.

readonly and const protect different things. const stops you from reassigning the variable (origin = somethingElse). readonly stops you from changing a property (origin.x = 10). A const variable can hold a perfectly mutable object, and a let variable can hold a read-only one.

Readonly<T>: read-only versions of existing types

Writing readonly on every property is tedious, and often you want both a mutable and a read-only version of the same type. The built-in Readonly<T> creates a copy of a type with every property marked readonly:

TypeScript Readonly of a type, and how shallow it is

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

The line marked @ts-expect-error really is an error, so the comment keeps the program compiling (Type Compatibility and Variance explains the comment). Notice that the output still shows fontSize: 20: the comment only silences the compiler, and the assignment runs anyway, because types never exist at runtime. The nested changes compile without any complaint, and the output shows shortcuts: [ 'ctrl+s', 'ctrl+k' ] and tabSize: 8. Readonly<T> is shallow: it marks shortcuts itself as read-only (you can't assign a new array to it), but the array it points to is still an ordinary string[]. A deep version comes later in this lesson.

Readonly<T> is a mapped type, and you'll meet the whole family in Built-in Utility Types.

Read-only arrays and tuples

Arrays have their own read-only type, with two spellings that mean exactly the same thing: readonly string[] and ReadonlyArray<string>. A read-only array has no mutating methods at all: no push, pop, splice, sort, reverse or fill, and index assignment is an error. Everything that returns a new array, such as map, filter, slice, concat and toSorted, still works:

TypeScript readonly arrays in function parameters

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

Passing the mutable scores to a readonly number[] parameter is fine: a mutable array has every method a read-only one has, and more. That's the main use of read-only arrays in everyday code: a parameter typed readonly T[] is a promise to the caller that the function won't change their array. Make it your default for parameters you only read.

The other direction isn't allowed, because the receiver could then mutate data that was promised to stay unchanged:

TypeScript Read-only arrays cannot become mutable (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

TEXT
main.ts(3,12): error TS2339: Property 'push' does not exist on type 'readonly string[]'.
main.ts(4,1): error TS2542: Index signature in type 'readonly string[]' only permits reading.
main.ts(10,16): error TS4104: The type 'readonly string[]' is 'readonly' and cannot be assigned to the mutable type 'string[]'.

If you really need a mutable copy, make one explicitly with [...frozenList] or frozenList.slice().

ReadonlyMap and ReadonlySet

Map and Set have read-only interfaces too. ReadonlyMap<K, V> keeps get, has, size, iteration and forEach but drops set, delete and clear. ReadonlySet<T> drops add, delete and clear. A common pattern is a class that keeps a mutable collection privately and exposes a read-only view:

TypeScript Exposing a read-only view of a Map

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

Look closely: the last line prints 0, not 15. The @ts-expect-error silences the compile error, but the call still runs, because the getter returns the real Map. A read-only type doesn't change the object. Without the comment the program wouldn't compile at all, which is the protection you actually rely on. If you need a guarantee even against code that bypasses the types (plain JavaScript callers, as casts), return a copy: new Map(this.#stock).

as const: read-only literals

Adding as const after an object or array literal tells TypeScript to infer the narrowest possible type: every property becomes readonly, every nested object and array too, arrays become read-only tuples, and values become literal types:

TypeScript as const makes literals deeply readonly

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

Unlike Readonly<T>, as const goes all the way down, because it applies to the literal as it's written. That makes it ideal for configuration and lookup tables. keyof, typeof and Indexed Access Types shows how to derive types such as Port from such constants.

A DeepReadonly type

For types you didn't write as literals, you can build a recursive version of Readonly<T>. This preview uses mapped and conditional types, which are explained fully later:

TypeScript A recursive DeepReadonly type

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

Arrays are objects, so the mapped branch handles them too and produces read-only arrays. Functions are left alone, so methods stay callable. In real projects, check whether a library you already use (such as type-fest) provides a well-tested deep readonly type before rolling your own.

readonly is not Object.freeze

readonly is purely a compile-time check. JavaScript's Object.freeze() is a runtime operation: it makes an object's own properties non-writable, and in strict-mode code (every ES module, including our editor's) an assignment throws. TypeScript knows this: Object.freeze(obj) returns Readonly<typeof obj>, and freezing an array gives readonly T[]:

TypeScript Object.freeze at runtime

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

The output shows Cannot assign to read only property 'x' of object '#<Object>', then that team.members grew to [ 'Ana', 'Bo' ] (freeze is shallow as well), and finally 2. That last part is a known gap: TypeScript lets you assign a type with readonly properties to one without them, so a second variable can change the "read-only" object. (Read-only arrays don't have this gap; that's the TS4104 error you saw earlier.)

readonly / Readonly<T> / as const Object.freeze()
When it acts Compile time only Runtime
Cost Zero, erased A call per object; small
Depth Shallow (as const and DeepReadonly go deep) Shallow
Bypassed by casts or JS code Yes No
Typical use Every API you design Shared constants exported to unknown code

Immutable update patterns

If you don't change data in place, you produce new versions of it. Modern JavaScript has a non-mutating method for almost every mutating one, so this stays short and readable:

TypeScript Updating read-only data by copying

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

Each update copies only the path to the change: the list and the one task that changed. Everything else is shared between versions, which is why the final line prints true. That structural sharing keeps immutable updates cheap, and it lets UI frameworks detect changes with a fast === comparison.

When you need a full, independent copy of plain data (for example to edit a draft), structuredClone(value) performs a deep copy of objects, arrays, Map, Set, dates and more. It doesn't copy functions or class prototypes. The JavaScript side of copying is covered in Copying Objects.

Choosing a level of protection

  • Mark parameters readonly T[] (or Readonly<T>) whenever a function only reads them. It's the cheapest and most useful habit.
  • Use readonly on fields and properties that should never change after creation, such as IDs and creation dates.
  • Use as const for literal configuration, lookup tables and lists of allowed values.
  • Use Object.freeze() at the boundary where values leave your control and might be changed by code that ignores types.
  • Reach for a deep readonly type when your whole state tree must be immutable, as in reducers and stores.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Given const s: Readonly<{ list: string[] }> = { list: [] };, which line compiles?

    Readonly is shallow. The property list cannot be reassigned, but the array it holds is still a mutable string[], so push is allowed.
  2. 2. Can you pass a number[] to a parameter of type readonly number[]?

    A mutable array has every member of a read-only array, so it is assignable. The opposite direction fails with TS4104. Nothing happens at runtime.
  3. 3. What is the type of ports in const c = { ports: [80, 443] } as const;?

    as const infers literal types and readonly tuples at every level of the literal.
  4. 4. What is the main difference between readonly and Object.freeze()?

    readonly never reaches the JavaScript output. Object.freeze runs at runtime and throws on assignment in strict mode. Both are shallow.
  5. 5. Which method can you call on a value of type readonly string[]?

    Read-only arrays keep only non-mutating methods. toSorted returns a new sorted array and leaves the original alone.

Summary

  • readonly blocks assignment to a property after creation; class fields may still be set in the constructor. const is about variables, readonly about properties.
  • Readonly<T> makes every property of a type read-only, but only one level deep.
  • readonly T[] (ReadonlyArray<T>), read-only tuples, ReadonlyMap and ReadonlySet remove mutating methods. Mutable values are assignable to them, not the other way round (TS4104).
  • as const makes a literal deeply read-only with literal types; a recursive DeepReadonly<T> does the same for any type.
  • All of these are compile-time only. Object.freeze() protects at runtime (shallowly), and mutable aliases can bypass readonly properties.
  • Update immutable data by copying: spread, map/filter, and toSorted, toReversed, toSpliced and with; unchanged parts are shared.

Next: Generics