Encapsulation is a fundamental principle of object-oriented programming that TypeScript fully supports. It's the practice of bundling data and methods that operate on that data within a single unit or object. This concept helps in hiding the internal details of how an object works, promoting better organization and security in your code.
Encapsulation offers several benefits:
TypeScript provides access modifiers to achieve encapsulation. The three main modifiers are:
class BankAccount {
private balance: number;
constructor(initialBalance: number) {
this.balance = initialBalance;
}
public deposit(amount: number): void {
this.balance += amount;
}
public withdraw(amount: number): boolean {
if (amount <= this.balance) {
this.balance -= amount;
return true;
}
return false;
}
public getBalance(): number {
return this.balance;
}
}
In this example, the balance
property is private, ensuring it can't be directly accessed or modified outside the class. Instead, public methods are provided to interact with the balance safely.
TypeScript also supports getters and setters, which provide a more elegant way to access and modify private properties:
class Circle {
private _radius: number;
constructor(radius: number) {
this._radius = radius;
}
get radius(): number {
return this._radius;
}
set radius(value: number) {
if (value > 0) {
this._radius = value;
} else {
throw new Error("Radius must be positive");
}
}
get area(): number {
return Math.PI * this._radius ** 2;
}
}
const circle = new Circle(5);
console.log(circle.radius); // 5
circle.radius = 10;
console.log(circle.area); // ~314.16
Getters and setters allow you to add logic when accessing or modifying properties, enhancing encapsulation while maintaining a clean interface.
To deepen your understanding of TypeScript and object-oriented programming, explore these related topics:
By mastering encapsulation, you'll write more robust, maintainable TypeScript code. It's a crucial concept that forms the foundation of effective object-oriented programming practices.