readonly (TypeScript)

`readonly` marks a property so it can be set once but never changed afterward. Trying to reassign it is a compile error, which protects values that shouldn't be mutated.

TypeScript

This is a compile-time guarantee, not a runtime lock — the type checker stops you, but the generated JavaScript has no special enforcement. It's great for ids and configuration that should stay constant.

There is also a `ReadonlyArray<T>` (and `readonly T[]`) type that prevents methods like push and pop from being called on an array.

Syntax

interface T { readonly id: number; }

Examples

TypeScript — Compile error: Cannot assign to 'id' because it is a read-only property.

interface Account {
  readonly id: number;
  balance: number;
}

const acc: Account = { id: 1, balance: 100 };
acc.id = 2;

Learn it in a lesson

See also

Back to the Dictionary