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 readonlyKey Points:
readonlymakes a property immutable after initialization.- Once a
readonlyproperty is set in the constructor (or through its default value), it cannot be reassigned. - Attempting to reassign a
readonlyproperty (likedad.name = "new name") will result in a compilation error.