Start Coding

Topics

Encapsulation in TypeScript

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.

Why Use Encapsulation?

Encapsulation offers several benefits:

  • Data protection: It prevents unauthorized access to an object's internal state.
  • Modularity: It allows for easier maintenance and modification of code.
  • Flexibility: Internal implementation can change without affecting external code.

Implementing Encapsulation in TypeScript

TypeScript provides access modifiers to achieve encapsulation. The three main modifiers are:

  • public: Accessible from anywhere (default)
  • private: Only accessible within the class
  • protected: Accessible within the class and its subclasses

Example: Basic Encapsulation


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.

Using Getters and Setters

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.

Best Practices for Encapsulation in TypeScript

  • Use private for internal properties that shouldn't be accessed directly.
  • Provide public methods for interacting with private data when necessary.
  • Consider using protected for properties that should be accessible in subclasses.
  • Utilize getters and setters for more controlled access to properties.
  • Keep the public interface of your classes minimal and well-documented.

Related Concepts

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.