A readonly
modifier is used in Typescript to specify a property as read-only, that is, the value of the property cannot be changed once it is initialized. This way we can make a property of a class immutable.
To declare a property as read-only we need to prefix it with the keyword readonly
.
class Student {
readonly id: number;
name: string;
constructor(id: number, name: string) {
this.id = id;
this.name = name;
}
}
let student = new Student(1, "Bob");
console.log(student); // Student {id: 1, name: 'Bob'}
In the above example, id
is a read-only property. If we want to change the id
of the object student, Typescript will throw an error.
student.id = 2; // error TS2540: Cannot assign to 'id'
// because it is a read-only property.
We can also specify the readonly keyword in the parameters of the constructor() method.
class Student {
constructor(readonly id: number, public name: string) {}
}
let student = new Student(1, "Bob");
console.log(student); // Student {id: 1, name: 'Bob'}
Note that we can access the value of a readonly property outside a class.
class Student {
constructor(readonly id: number, public name: string) {}
}
let student = new Student(1, "Bob");
console.log(student.id); // 1