The readonly modifier in TypeScript
With the readonly
modifier, properties can be made read-only. Let's look at an example. Let's make the User
class property name
read-only:
class User {
readonly name: string;
constructor(name: string) {
this.name = name;
}
}
Let's create an object of the class, assigning some value to the name:
let user: User = new User('john');
Let's read the meaning of the name:
console.log(user.name); // 'john'
But trying to write a different value to the property will result in an error:
user.name = 'eric'; //
Give the User
class a read-only property age
. Create an object of this class and print its age to the screen.