Read-only properties and index signatures

A property or index signature can now be declared with the readonly modifier is considered read-only.

Read-only properties may have initializers and may be assigned to in constructors within the same class declaration, but otherwise assignments to read-only properties are disallowed.

In addition, entities are implicitly read-only in several situations:

  • A property declared with a get accessor and no set accessor is considered read-only.
  • In the type of an enum object, enum members are considered read-only properties.
  • In the type of a module object, exported const variables are considered read-only properties.
  • An entity declared in an import statement is considered read-only.
  • An entity accessed through an ES2015 namespace import is considered read-only (e.g. foo.x is read-only when foo is declared as import * as foo from "foo").

Example

  1. interface Point {
  2. readonly x: number;
  3. readonly y: number;
  4. }
  5. var p1: Point = { x: 10, y: 20 };
  6. p1.x = 5; // Error, p1.x is read-only
  7. var p2 = { x: 1, y: 1 };
  8. var p3: Point = p2; // Ok, read-only alias for p2
  9. p3.x = 5; // Error, p3.x is read-only
  10. p2.x = 5; // Ok, but also changes p3.x because of aliasing
  1. class Foo {
  2. readonly a = 1;
  3. readonly b: string;
  4. constructor() {
  5. this.b = "hello"; // Assignment permitted in constructor
  6. }
  7. }
  1. let a: Array<number> = [0, 1, 2, 3, 4];
  2. let b: ReadonlyArray<number> = a;
  3. b[5] = 5; // Error, elements are read-only
  4. b.push(5); // Error, no push method (because it mutates array)
  5. b.length = 3; // Error, length is read-only
  6. a = b; // Error, mutating methods are missing