Stable object fields
Define configuration or domain objects whose identity fields should not be reassigned after construction.
TypeScript · Const
The readonly property modifier lets an object property be assigned during initialization but prevents later assignments through that property. It is a compile-time, shallow protection rather than runtime deep immutability.
Prefix an interface property with readonly to make it assignable when the object is created but not writable afterward through that property. This restriction is enforced by TypeScript’s type system, so it does not make the referenced value deeply immutable or alter runtime behavior.
readonly propertyName: Type;interface Point {
readonly x: number;
readonly y: number;
}
const point: Point = { x: 10, y: 20 };
console.log(point.x, point.y);
// point.x = 15; // Error: cannot assign to a readonly property
The interface permits reading the coordinates while preventing assignments to them during type-checking.
Define configuration or domain objects whose identity fields should not be reassigned after construction.
Publish APIs that expose collection data without allowing callers to mutate the collection through the returned reference.
Model coordinates, identifiers, or other value objects that should remain fixed after creation.
readonly is a property modifier that prevents assignments to that property during type-checking after initialization. It is appropriate for object properties whose value should not be replaced by consumers.
Follow-up: Does readonly create runtime immutability? No. It is a compile-time restriction and does not change JavaScript runtime behavior.
const applies to variables, while readonly applies to properties. A const variable cannot be rebound, whereas a readonly property cannot be assigned through that property after creation.
Follow-up: Can a readonly property hold mutable data? Yes; the property reference cannot be replaced, but the referenced value may still be changed unless its own type prevents mutation.
A readonly property is shallow: it blocks rewriting the property itself but does not recursively freeze nested objects. Use readonly array or tuple types when the collection’s mutating operations should be unavailable through that reference.
Follow-up: What type represents an array that should not be mutated? ReadonlyArray<T> provides an array view with mutating methods removed.
ReadonlyArray<T>readonly tuplesconstReadonly<Type>