I’m creating a base class that will be used to validate the coordinates property in the setter. Being new to Typescript and Javascript, I’m not sure what I’m doing but it seems as though it’s the right way to do validation cleanly.
As of now I have a base class Base
setup and the child class Property
extending it.
export default class Base {
_coord: number = 0;
set coord(coord: number) {
console.log(coord);
}
}
Property
sets coord
in the constructor which lets me validate it from the child class. My question is: what is the difference between using this._coord
and this.coord
from the child class? I have tried setting coord
with this._coord
which doesn’t use the setter method in the base so I’m using this.coord:
export class Property extends Base {
address: string;
postcode: number;
bedrooms: number;
constructor(address: string,
postcode: number,
bedrooms: number) {
super();
this.address = address;
this.postcode = postcode;
this.bedrooms = bedrooms;
this.coord = 100; // Setting base property
}
}
Lelstz is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.
1
_coord
and coord
are completely different properties of your class. You could name them completely different. Seems _coord
is where you want to store your value after validation. So you could avoid accidentaly using it directly by marking it private. Or you can use a private JS property #coord
. That way you’d ensure always pass through the validation when assigning:
export default class Base {
private _coord: number = 0;
set coord(coord: number) {
console.log(coord);
// some validation here
this._coord = coord;
}
get coord(){
return this._coord;
}
}