Advertisement
Intermediate TypeScript, Readonly, const Assertions & Immutability

Is 'readonly' at the type level enforced at runtime, and how can a readonly property still be mutated via a workaround?

Short answer

'readonly' is a compile-time-only restriction, completely erased from the emitted JavaScript — at runtime, the property is a perfectly normal, mutable value, so any code that bypasses the type checker (like a type assertion, plain JavaScript caller, or Object.assign) can still…

Save TypeScript mock interview
Advertisement
AModel answer
'readonly' is a compile-time-only restriction, completely erased from the emitted JavaScript — at runtime, the property is a perfectly normal, mutable value, so any code that bypasses the type checker (like a type assertion, plain JavaScript caller, or Object.assign) can still mutate it without any runtime error.
interface Point { readonly x: number; }
const p: Point = { x: 1 };
(p as { x: number }).x = 99; // bypasses readonly via a type assertion, mutates fine at runtime
console.log(p.x); // 99
Real-world example
Understanding that 'readonly' is a development-time safety net, not a genuine runtime immutability guarantee like Object.freeze().
Likely follow-ups
  • How would you combine 'readonly' with Object.freeze() to get BOTH compile-time and runtime immutability?
Related topics