readonly Properties
Mark object properties as immutable after initialization.
The readonly Modifier
The readonly modifier marks a property that can be set once but never reassigned afterward. It expresses immutability at the type level, helping prevent accidental changes.
interface Point {
readonly x: number;
readonly y: number;
}
const p: Point = { x: 1, y: 2 };
console.log(p.x, p.y);
// p.x = 5; // Error: cannot assign to readonly propertyreadonly on Interfaces
On an interface, readonly documents which fields are fixed after creation. Consumers can read them freely but the compiler blocks any reassignment.
interface Config {
readonly env: string;
retries: number; // mutable
}
const c: Config = { env: 'prod', retries: 3 };
c.retries = 5; // allowed
console.log(c.env, c.retries);