Advertisement
Beginner TypeScript, Readonly, const Assertions & Immutability

How does the 'readonly' modifier on an interface property differ from using 'const' for a variable?

Short answer

'const' prevents REASSIGNING a variable binding itself, but doesn't stop you from mutating an object it points to; 'readonly' on a property prevents REASSIGNING that specific property after the object is created, while the object binding itself might still be a regular mutable…

Save TypeScript mock interview
Advertisement
AModel answer
'const' prevents REASSIGNING a variable binding itself, but doesn't stop you from mutating an object it points to; 'readonly' on a property prevents REASSIGNING that specific property after the object is created, while the object binding itself might still be a regular mutable 'let' or 'const' variable.
interface Point { readonly x: number; readonly y: number; }
const p: Point = { x: 1, y: 2 };
// p.x = 5; // Error: cannot assign to 'x' because it is a read-only property
p.x; // fine to read
Real-world example
Preventing accidental mutation of a coordinate, configuration, or value object's fields after construction.
Likely follow-ups
  • Does 'readonly' provide any actual runtime enforcement, or is it purely compile-time?
Related topics