readonly (modifier)

Prevents reassignment of a property or array element after initialization.

Since TS 2.0 Spec ↗

Syntax

readonly propertyName: Type

Examples

class Point {
  readonly x: number;
  constructor(x: number) {
    this.x = x; // allowed in constructor
  }
}
// new Point(1).x = 2; // Error
const tuple: readonly [number, string] = [1, 'a'];
function sum(ns: readonly number[]) {}

Notes

The `readonly` property modifier is enforced at compile time only. Properties may still be assigned within the declaring class constructor. Combine with arrays or tuples for immutable collections, or use the `Readonly<T>` utility for whole-object immutability. It does not deep-freeze nested objects.

See also