Readonly and Parameter Properties

readonly Class Members

A readonly property can be assigned only in its declaration or in the constructor.

Example

Parameter properties combine the declaration and the assignment: constructor(private readonly repo: Repo) is the standard style for dependency injection in NestJS and Angular.

class ProductRepository {
  private data = new Map<number, string>([[1, "Keyboard"], [2, "Mouse"]]);
  find(id: number): string | undefined {
    return this.data.get(id);
  }
}

class ProductService {
  constructor(
    private readonly repo: ProductRepository,
    public readonly currency: string = "INR",
  ) {}

  title(id: number): string {
    return this.repo.find(id) ?? "Unknown product";
  }
}

const service = new ProductService(new ProductRepository());
console.log(service.title(2), service.currency);
console.log(service.title(9));

Output

Mouse INR
Unknown product

Changing a readonly Property

Example

Assigning to readonly outside the constructor gives TS2540.

class Order {
  constructor(public readonly id: string) {}

  reset(): void {
    this.id = "";
  }
}

Compiler output (tsc)

Line 5: error TS2540: Cannot assign to 'id' because it is a read-only property.