Skip to the solution
EasyFrontend10 min read

How do you make values immutable in TypeScript?

1.1k views

The problem

Question presented to candidate: "How do you make values immutable in TypeScript? Walk me through the tools, and tell me which ones actually stop a value changing at run time."

What a strong answer should cover:

  • const only stops re-assigning the variable; the object it points to can still be changed
  • Compile-time tools: readonly properties, Readonly<T>, readonly T[] / ReadonlyArray<T>, ReadonlyMap / ReadonlySet, as const, and a recursive DeepReadonly<T> for nested data
  • Run-time tool: Object.freeze (typed as Readonly<T>), which is shallow, fails silently in sloppy mode and throws in strict mode; a deepFreeze helper for nested data
  • The limits: all of the type-level tools are erased and shallow, and readonly object properties do not affect assignability, so a mutable alias can still write
  • Classes: readonly fields set once in the constructor, #private fields with a getter for computed read-only state
  • The everyday pattern: update by creating new objects ({ ...p, y: 3 }) rather than writing in place

Clarifying questions expected:

  • Do we need run-time protection (shared config, untrusted plugins) or is a compile-time guarantee enough?
  • How deep is the data: a flat config object or nested state such as a Redux store?

Code / implementation expected: Optional β€” a readonly interface, Readonly<T> and Object.freeze, with one rejected write.

  • readonly
  • immutability

Try it yourself

Sketch your approach before you read the solution. That is what the interview tests.

Stuck? Get a hint.

A short nudge toward the approach. It will not give the answer away.

Solution

The solution is hidden so you can try first

10 min read Β· 11 sections

Run the code

Edit the code and run it here. Each console line with an expected value becomes a test.

TypeScriptFrom const to Object.freeze: what each layer stops
TypeScriptDeepReadonly, deepFreeze and readonly class fields

Discussion

Other approaches, follow-ups and how it went in real interviews.

Sign in to join the discussion.

No comments yet. Share how you would answer it.

Question 2 of 81 in TypeScript

Keep your momentum going.

Mark this question solved to track your progress, then take the next one while it is fresh.

Up nextEasy

How does type inference work in TypeScript?

Continue