TypeScript provides three access modifiers:
public
(default): Accessible everywhereprivate
: Accessible only within the same classprotected
: Accessible within the class and its subclassesclass 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
}
}