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:
constonly stops re-assigning the variable; the object it points to can still be changed- Compile-time tools:
readonlyproperties,Readonly<T>,readonly T[]/ReadonlyArray<T>,ReadonlyMap/ReadonlySet,as const, and a recursiveDeepReadonly<T>for nested data - Run-time tool:
Object.freeze(typed asReadonly<T>), which is shallow, fails silently in sloppy mode and throws in strict mode; adeepFreezehelper 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:
readonlyfields set once in the constructor,#privatefields 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.