What are access modifiers in TypeScript?

Beginner

Answer

TypeScript provides three access modifiers:

  • public (default): Accessible everywhere
  • private: Accessible only within the same class
  • protected: Accessible within the class and its subclasses
class BankAccount {
  public accountNumber: string;
  private balance: number;
  protected accountType: string;

  constructor(accountNumber: string, initialBalance: number) {
    this.accountNumber = accountNumber;
    this.balance = initialBalance;
    this.accountType = "savings";
  }

  public getBalance(): number {
    return this.balance; // Accessing private property within class
  }

  private calculateInterest(): number {
    return this.balance * 0.05;
  }
}

class PremiumAccount extends BankAccount {
  constructor(accountNumber: string, initialBalance: number) {
    super(accountNumber, initialBalance);
    // this.balance; // Error: private property
    console.log(this.accountType); // OK: protected property
  }
}