Readonly Modifier
What
The readonly modifier allows you to mark specific object properties as immutable. Once initialized, these properties cannot be reassigned.
How
Add the readonly keyword before the property name in your type definition:
type Point = {
readonly x: number;
y: number;
};
const p: Point = { x: 10, y: 20 };
p.y = 30; // OK
p.x = 15; // Error: Cannot assign to 'x' because it is a read-only property
Why
readonly is a powerful tool for preventing accidental state changes in your application. It encourages a more functional approach to programming where data is transformed into new objects rather than mutated in place, making your code easier to reason about.
Summary
Use readonly for properties that should represent constant state once an object is created.