Getters and setters
| get syntax | |
| set with validation | |
| Backing fields | |
| When accessors win |
get syntax
A getter looks like a field to callers but runs a method behind the scenes. Use get to compute a value from current state on every read.
class Temp {
celsius: number = 0;
get fahrenheit(): number {
return this.celsius * 1.8 + 32;
}
}
const temp = new Temp();
console.log(temp.fahrenheit);
set with validation
A setter runs on every write, so it is the right place to check values. Reject bad input before it reaches the stored state.
class User {
private ageValue: number = 0;
get age(): number {
return this.ageValue;
}
set age(value: number) {
if (value >= 0) {
this.ageValue = value;
}
}
}
Backing fields
A backing field holds the real data while the accessor controls the door. The accessor must read and write the backing field, never itself, or the call will loop forever.
class User {
private nameValue: string = "Guest";
get name(): string {
return this.nameValue;
}
set name(value: string) {
this.nameValue = value.trim();
}
}
When accessors win
Reach for accessors when reads need computing or writes need guarding. Plain fields stay better for simple storage with no rules attached.
Start with a plain field and upgrade to a getter and setter only when real logic appears.
class Order {
count: number = 1;
price: number = 10;
get total(): number {
return this.count * this.price;
}
}
Next: Enums
Article author: Arthur Isaev