Access Modifiers and Encapsulation in TypeScript

In object-oriented programming, encapsulation is the practice of hiding internal implementation details of a class and providing access to its members through well-defined interfaces. TypeScript, as a superset of JavaScript, supports encapsulation through the use of access modifiers.

Access Modifiers

In TypeScript, access modifiers are keywords used to define the accessibility of class members (properties and methods). They determine whether a member can be accessed from within its own class (internal access) or from outside the class (external access). TypeScript provides three access modifiers: public, private, and protected.

1. Public

The public access modifier allows unrestricted access to a class member from any other part of the program. By default, all members in TypeScript are considered public, even if the keyword is not explicitly specified. Here's an example:

class Person {
  public name: string;

  public sayHello() {
    console.log(`Hello, ${this.name}!`);
  }
}

const person = new Person();
person.name = 'John';
person.sayHello();  // Output: Hello, John!

In this example, the name property and the sayHello method are both public. They can be accessed and modified from any part of the program.

2. Private

The private access modifier restricts access to a class member only within its own class. It cannot be accessed or modified from outside the class. Here's an example:

class Person {
  private age: number;

  private getAge() {
    return this.age;
  }
}

const person = new Person();
person.age = 25;  // Error: Property 'age' is private
console.log(person.getAge());  // Error: Property 'age' is private

In this example, the age property and the getAge method are both private. Any attempt to access or modify the age property or call the getAge method from outside the Person class will result in a compiler error.

3. Protected

The protected access modifier allows a class member to be accessed within its own class and its subclasses but not from outside the class hierarchy. Subclasses can inherit and access protected members of their parent class. Here's an example:

class Animal {
  protected legs: number;

  protected displayLegs() {
    console.log(`I have ${this.legs} legs.`);
  }
}

class Dog extends Animal {
  constructor() {
    super();
    this.legs = 4;
  }
}

const dog = new Dog();
dog.displayLegs();  // Output: I have 4 legs.

In this example, the legs property and the displayLegs method are both protected. The Dog class, which extends the Animal class, can access and modify the legs property and call the displayLegs method.

Encapsulation

Encapsulation, in the context of object-oriented programming, is achieved by combining access modifiers with the organization of data and methods within a class. By hiding the internal details and exposing only necessary interfaces, encapsulation facilitates better maintainability, reusability, and security of code.

Encapsulating data involves making class properties private or protected and providing access to them through getter and setter methods. Here's an example:

class BankAccount {
  private balance: number;

  constructor(initialBalance: number) {
    this.balance = initialBalance;
  }

  public deposit(amount: number) {
    this.balance += amount;
  }

  public withdraw(amount: number) {
    if (amount <= this.balance) {
      this.balance -= amount;
    } else {
      console.log('Insufficient balance.');
    }
  }

  public getBalance(): number {
    return this.balance;
  }
}

const account = new BankAccount(1000);
account.deposit(500);
account.withdraw(200);
console.log(account.getBalance());  // Output: 1300

In this example, the balance property is private to ensure it cannot be directly manipulated from outside the class. The deposit, withdraw, and getBalance methods provide the necessary interfaces to interact with the balance property.

Encapsulation not only allows you to control the modification of internal data but also enables the class to maintain its state and perform necessary validation or operations when accessing or modifying its properties.

Conclusion

Access modifiers and encapsulation are important concepts in TypeScript that help you achieve better organization, security, and reusability of your code. By properly defining access levels and encapsulating internal details, you can create robust and maintainable software systems.


noob to master © copyleft