Jak odpowiedział @Vitaliy Ulantikov, można użyć readonlymodyfikatora na właściwości. To działa dokładnie tak samo jak getter.
interface Point {
readonly x: number;
readonly y: number;
}
Gdy dosłowne obiekt implementuje interfejs, nie można nadpisać readonlywłaściwość:
let p1: Point = { x: 10, y: 20 };
p1.x = 5; // error!
Ale gdy klasa implementuje interfejs, nie ma sposobu, aby uniknąć nadpisania go.
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!
}
}
Myślę, że to dlatego, że gdy ponownie zadeklarować właściwości w definicji klasy, które zastępują właściwości interfejsu, a nie są już tylko do odczytu.
Aby to naprawić, należy readonlyna właściwości bezpośrednio w klasie, która implementuje interfejs
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!
}
}
Przekonaj się na placu zabaw .