As @Vitaliy Ulantikov answered, you may use the readonly
modifier on a property. This acts exactly like a getter.
interface Point {
readonly x: number;
readonly y: number;
}
When an object literal implements the interface, you cannot overwrite a readonly
property:
let p1: Point = { x: 10, y: 20 };
p1.x = 5; // error!
But when a class implements the interface, there is no way to avoid overwriting it.
class PointClassBroken implements Point {
// these are required in order to implement correctly
x: number;
y: number;
constructor(x: number, y: number) {
this.x = x
this.y = y
}
changeCoordinates(x: number, y: number): void {
this.x = x // no error!
this.y = y // no error!
}
}
I guess that’s because when you re-declare properties in the class definition, they override the properties of the interface, and are no longer readonly.
To fix that, use readonly
on the properties directly in the class that implements the interface
class PointClassFixed implements Point {
readonly x: number;
readonly y: number;
constructor(x: number, y: number) {
this.x = x
this.y = y
}
changeCoordinates(x: number, y: number): void {
this.x = x // error!
this.y = y // error!
}
}
See for yourself in the playground.