Careeroza
Getters and Setters
get and set
Accessors look like properties from outside but run code. Use a getter for computed values and a setter to validate assignments.
Example
class CartItem {
private _qty = 1;
constructor(public name: string, public unitPrice: number) {}
get qty(): number {
return this._qty;
}
set qty(value: number) {
if (!Number.isInteger(value) || value < 1 || value > 10) {
throw new RangeError("Quantity must be 1 to 10");
}
this._qty = value;
}
get lineTotal(): number {
return this.unitPrice * this._qty;
}
}
const item = new CartItem("Mango Box", 450);
item.qty = 3;
console.log(item.qty, item.lineTotal);
try {
item.qty = 25;
} catch (e) {
console.log((e as Error).message);
}Output
3 1350 Quantity must be 1 to 10
Getter Without a Setter is Readonly
Example
A property with only get cannot be assigned (TS2540).
class Circle {
constructor(private r: number) {}
get area(): number { return Math.PI * this.r ** 2; }
}
const c = new Circle(2);
c.area = 10;Compiler output (tsc)
Line 7: error TS2540: Cannot assign to 'area' because it is a read-only property.