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