readOnly Option in TypeScript Interface
· One min read
When defining the structure of an object using interface keyword, we can specify readonly modifier.
interface Car {
readonly model: string;
show(message: string): void;
}
If any object implements Car interface, there should be a property called model. It should be initialized only once and cannot be changed.
So how it works?
Here is an object that implements the interface Car.
let obj: Car = {
model: "BMW",
show: () => {},
};
Immediately after initialization, if we try to update the model property, TypeScript will throw error.
obj.model = "Audi";
Above line throws below error:
Cannot assign to 'model' because it is a read-only property.