Translate

Saturday 17 February 2024

What are Access Modifiers in Typescript ? 068

  What are Access Modifiers in Typescript ?


Access modifiers in TypeScript control the visibility and accessibility of members (properties, methods) within a class, interface, or enum. They play a crucial role in encapsulating data and promoting proper object-oriented design. Here's a breakdown of the three main access modifiers:

1. Public:

  • Members declared as public are accessible from anywhere in the code, regardless of scope or module.

  • This level of accessibility should be used cautiously, as it exposes members freely, potentially hindering maintainability and encapsulation.

  • Use public for members meant to be widely used by other parts of your code.

Example:


TypeScript

class Person {
  public name: string; // Public property can be accessed from anywhere

  public greet() {
    console.log(`Hello, my name is ${this.name}`); // Public method can be called from anywhere
  }
}

2. Private:

  • Members declared as private are only accessible within the class itself, not outside.

  • This promotes encapsulation by hiding implementation details and preventing unintended modifications from external code.

  • Use private for members that should not be directly accessed or modified from outside the class.

Example:


TypeScript

class Product {
  private price: number; // Private property cannot be accessed directly

  public getPrice() {
    return this.price; // Public getter method provides controlled access
  }
}

3. Protected:

  • Members declared as protected are accessible within the class itself and its subclasses, but not outside the class hierarchy.

  • This allows subclasses to inherit and potentially modify protected members while maintaining encapsulation within the family of related classes.

  • Use protected for members meant to be shared and potentially customized by subclasses.

Example:


TypeScript

class Animal {
  protected health: number; // Protected property can be accessed by subclasses

  protected heal() {
    this.health += 10; // Protected method can be overridden in subclasses
  }
}

class Dog extends Animal {
  bark() {
    console.log("Woof!");
    this.heal(); // Accessing protected method from subclass
  }
}

Choosing the Right Modifier:

  • Start with private by default to maximize encapsulation and data protection.

  • Use public sparingly for members that need to be accessed widely, considering alternative approaches like getter/setter methods for controlled access.

  • Use protected for members intended for customization within a class hierarchy.

By effectively using access modifiers, you can create more modular, maintainable, and secure TypeScript code, promoting good object-oriented design principles.


No comments:

Post a Comment

Note: only a member of this blog may post a comment.