A readonly property can be set when the object is created, or inside a class constructor, and never reassigned after that. The compiler rejects any later assignment.
interface Point {
readonly x: number;
readonly y: number;
}
const point: Point = { x: 10, y: 20 };
// point.x = 30; // Error: Cannot assign to 'x' because it is read-only
// Readonly arrays
const readonlyArray: readonly number[] = [1, 2, 3];
// readonlyArray.push(4); // Error: Property 'push' does not exist
// ReadonlyArray type
const numbers: ReadonlyArray<number> = [1, 2, 3];
For arrays, readonly number[] and ReadonlyArray<number> remove methods that change the array, such as push. Readonly<T> makes every property of a type read-only at once.
The check is compile-time only, and nothing freezes the object at runtime. It is also shallow: a readonly property that holds an object still lets you change that object's fields.
const is different, because it stops a variable from being reassigned, while readonly applies to properties.
This answer doesn't lend itself to a diagram - it reads best . No credits were charged.
Why there's no diagram: “”
The interactive diagram is below the answer - jump to diagram ↓ · Below it, the related concept . Jump to it ↓
The diagram below the answer is the concept . Jump to it ↓