In TypeScript, the readonly modifier makes a property immutable. Once a property is set, it cannot be reassigned after the object has been created. This is useful for creating constant properties that should not be modified.

Example: readonly Properties

class Octopus {
  readonly name: string;  // readonly property
  readonly numberOfLegs: number = 8;  // readonly property with default value
 
  constructor(theName: string) {
    this.name = theName;
  }
}
 
let dad = new Octopus("Man with the 8 strong legs");
dad.name = "Man with the 3-piece suit";  // Error: 'name' is readonly

Key Points:

  1. readonly makes a property immutable after initialization.
  2. Once a readonly property is set in the constructor (or through its default value), it cannot be reassigned.
  3. Attempting to reassign a readonly property (like dad.name = "new name") will result in a compilation error.