Just recently discovered about using get and set keywords for class properties I was wondering what is the preferred method when using get / set for typescript classes:
class example {
private a: any;
private b: any;
getA(): any{
return this.a;
}
setA(value: any){
this.a = value;
}
get b(): any{
return this.b;
}
set b(value: any){
this.b = value;
}
}
I am just curious if there are any best practices, performance, or other factors.
Getter and Setters have several uses, like
You can make a private variable read only, if you don't specify a setter
class example {
private _a: any;
get a(): any{
return this._a;
}
}
You can use them to execute a custom logic when a variable changes, sort of a replacement for Event Emitter
class example {
private _a: any;
set a(value: any){
this._a = value;
// Let the world know, I have changed
this.someMethod();
}
someMethod() {
// Possibly a POST API call
}
}
You can use them to alias an output
class Hero {
private _health: any = 90;
get health(): string {
if(this._health >= 50) {
return "I am doing great!";
} else {
return "I don't think, I'll last any longer";
}
}
}
A setter can be used for a clean assignment
class Hero {
private _a: number;
set a(val: number) {
this._a = val;
}
setA(val: number) {
this._a = val;
}
constructor() {
this.a = 30; // Looks cleaner
this.setA(50); // Looks Shabby, Method's purpose is to perform a logic not handle just assignments
}
}
Finally setter's biggest strength is the ability to check variables for proper value before assignment
class Hero {
private _age: number;
set age(age: number) {
if (age > 0 && age < 100) {
this._age = age
} else {
throw SomeError;
}
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With