Getters and Setters
In this page:
Basic Getter
A getter is declared with the get keyword and is accessed like a plain property rather than called like a method, which is useful for exposing a computed or validated value behind ordinary property syntax.
Example: Basic Getter
class Circle {
constructor(private radius: number) {}
get area(): number {
return 3.14 * this.radius ** 2;
}
}
const c = new Circle(5);
console.log(c.area); // accessed like a property
Basic Setter
A setter is declared with the set keyword and is invoked using assignment syntax; setters allow a class to intercept every write to a property instead of allowing direct, unchecked field access.
Example: Basic Setter
class Person {
private _name: string = "";
set name(value: string) {
this._name = value;
}
get name(): string {
return this._name;
}
}
const p = new Person();
p.name = "Kavya";
console.log(p.name);
Validation with Setters
Setters can validate incoming values before assigning them, throwing or ignoring an invalid update, which helps keep an object's internal state always in a consistent, trustworthy shape.
Example: Validation with Setters
class Account {
private _balance: number = 0;
set balance(value: number) {
if (value < 0) throw new Error("Balance cannot be negative");
this._balance = value;
}
get balance(): number {
return this._balance;
}
}
const acc = new Account();
acc.balance = 100;
console.log(acc.balance);
Computed Getters
A getter can calculate a value from one or more internal properties on the fly, which keeps derived values in sync automatically instead of requiring the class to remember to update a separate cached field.
Example: Computed Getters
class Rectangle {
constructor(public width: number, public height: number) {}
get area(): number {
return this.width * this.height;
}
}
console.log(new Rectangle(4, 5).area);
Using Getters and Setters Together
Getters and setters are often paired to provide a property-like interface to callers while keeping the underlying storage private, hiding implementation details behind syntax that still looks like a simple field access.
Example: Using Getters and Setters Together
class Temperature {
private _celsius: number = 0;
get fahrenheit(): number {
return this._celsius * 9 / 5 + 32;
}
set fahrenheit(value: number) {
this._celsius = (value - 32) * 5 / 9;
}
}
const t = new Temperature();
t.fahrenheit = 98.6;
console.log(t.fahrenheit);
Chapter Quiz — Complete all 9 topics to unlock
0/9 topics done
Complete these topics first: