Readonly properties
In addition to the public, private, and protected access modifiers, we can also mark a class property as readonly. This means that, once the value of the property has been set, it is not able to be modified, either by the class itself, or by any users of the class. There is only one place where a readonly property can be set, and this is within the constructor function itself. Consider the following code:
class ClassWithReadOnly { readonly name: string; constructor(_name : string) { this.name = _name; } setReadOnly(_name: string) { // generates a compile error this.name = _name; } }
Here, we have defined a class named ClassWithReadOnly that has a name property of the string type that has been marked with the readonly keyword. The constructor function is setting this value. We have then defined a second function named setReadOnly, where we are attempting to set this readonly property. This code will generate the following error:
error TS2540: Cannot assign to 'name' because it is a constant or a read-only property.
This error message is telling us that the only place where a readonly property can be set is in the constructor function.