Getters and setters are special methods that provide controlled access to object properties in TypeScript. They allow you to define how a property is accessed or modified, enabling better encapsulation and data validation.
Getters are methods that retrieve the value of a property. They're defined using the get
keyword followed by the property name.
class Circle {
private _radius: number;
get radius(): number {
return this._radius;
}
}
Setters are methods that set the value of a property. They're defined using the set
keyword followed by the property name.
class Circle {
private _radius: number;
set radius(value: number) {
if (value >= 0) {
this._radius = value;
}
}
}
Often, getters and setters are used together to provide controlled access to a property:
class Circle {
private _radius: number;
get radius(): number {
return this._radius;
}
set radius(value: number) {
if (value >= 0) {
this._radius = value;
} else {
throw new Error("Radius cannot be negative");
}
}
}
const circle = new Circle();
circle.radius = 5; // Sets the radius
console.log(circle.radius); // Gets the radius
To deepen your understanding of TypeScript and object-oriented programming, explore these related topics:
By mastering getters and setters, you'll enhance your ability to create robust and maintainable TypeScript code. These accessor methods are fundamental to implementing encapsulation, a key principle of object-oriented programming.