readonly keyword in typescript:
readonly keyword in TypeScript makes one property in type, class or interface read-only. readonly prefix is used to make a property readonly.
Let me show you a couple of examples of readonly:
readonly in a class:
readonly properties cannot be changed. It is read-only i.e. we can only read its value. If we make any property readonly in a class, they need to be initialized in the constructor or should be initialized with a value.
For example:
class Student{
readonly name: string;
constructor(name: string){
this.name = name;
}
}
let student = new Student('Alex');
Here,
- name is a readonly property. So, we can only initialize it only in the constructor. We can’t assign its value later on.
readonly in an interface:
readonly can also be used in an interface as like below:
interface IStudent {
readonly name: string;
}
let student: IStudent = {
name: 'Alex'
}
console.log(student.name)
Readonly type:
We can use Readonly
interface IStudent {
name: string;
}
let student: Readonly<IStudent> = {
name: 'Alex'
}
console.log(student.name)
For any of these examples, if we try to edit the readonly value, it will throw one compile error.