Careeroza
Access Modifiers
public, private and protected
| Modifier | Accessible from | Default? |
|---|---|---|
public | anywhere | yes (if you write nothing) |
protected | the class and its subclasses | no |
private | only inside the class itself | no |
Example
class Account {
public holder: string;
protected balance: number;
private pin: string;
constructor(holder: string, balance: number, pin: string) {
this.holder = holder;
this.balance = balance;
this.pin = pin;
}
checkPin(input: string): boolean {
return input === this.pin;
}
}
class SavingsAccount extends Account {
addInterest(ratePercent: number): number {
this.balance += (this.balance * ratePercent) / 100; // protected: OK in subclass
return this.balance;
}
}
const acc = new SavingsAccount("Neha", 10000, "4321");
console.log(acc.holder, acc.checkPin("1111"), acc.addInterest(4));Output
Neha false 10400
Breaking the Rules
Example
Reading private or protected members from outside is an error (TS2341 and TS2445).
class Account {
protected balance = 100;
private pin = "4321";
}
const acc = new Account();
console.log(acc.balance);
console.log(acc.pin);Compiler output (tsc)
Line 7: error TS2445: Property 'balance' is protected and only accessible within class 'Account' and its subclasses. Line 8: error TS2341: Property 'pin' is private and only accessible within class 'Account'.
Note: private and protected are checked only by the compiler. In the JavaScript output they are normal properties and console.log(acc) still shows them.