readonly

A modifier that blocks changing a field after the object is created.

On this page

Example

#
TypeScript
interface Certificate {
  readonly id: string
  readonly issuedAt: string
  owner: string
}

const cert: Certificate = { id: 'CW-2026-001', issuedAt: '2026-09-28', owner: 'Emma' }
cert.owner = 'Emma Carter'

console.log(cert)
Result
{ id: 'CW-2026-001', issuedAt: '2026-09-28', owner: 'Emma Carter' }

Definition and usage

#

The readonly modifier before a field name means that once the object is created, it can no longer be changed. Trying to assign a new value ends in a compile error.

This protection works at the type level, not in the running program: after compiling to JavaScript, the object can still be changed. To block it at runtime, use Object.freeze().

readonly also works in classes (a field set only in the constructor) and with arrays (readonly string[]). For an entire type at once, use Readonly<T>.

Syntax

#
Syntax
interface Name {
  readonly field: type
}

More examples

#
Trying to change a readonly field
TypeScript
cert.id = 'CW-2026-999'
// Error: Cannot assign to 'id' because it is a read-only property.

Good practices

#
  • Mark identifiers and creation dates as readonly. Fields like that shouldn’t change.
  • Remember that readonly is shallow: a nested object can still be modified.

Related entries

#

Spotted a mistake or missing an example? Write to us.