Syntax
public prop: type;
private prop: type;
protected prop: type;Examples
The Three Modifiers
Controlling exactly where each property/method can be accessed from.
class BankAccount {
public accountHolder: string;
private balance: number;
protected accountNumber: string;
constructor(holder: string, initialBalance: number, accountNumber: string) {
this.accountHolder = holder;
this.balance = initialBalance;
this.accountNumber = accountNumber;
}
public getBalance(): number {
return this.balance; // accessing private balance is fine from WITHIN the class
}
}
const account = new BankAccount("Alice", 1000, "ACC-001");
console.log(account.accountHolder); // OK - public
// console.log(account.balance); // Error - privateprotected in Subclasses
protected members remain accessible to subclasses, unlike private ones.
class SavingsAccount extends BankAccount {
showAccountNumber(): string {
return this.accountNumber; // OK - protected is accessible in subclasses
// return this.balance; // Error - private is NOT accessible, even in a subclass
}
}Best practices
- Default to private for internal implementation details, exposing only what genuinely needs to be part of the class's public API
- Use protected specifically when subclasses legitimately need access to a member that outside code should not have
- Remember these modifiers are compile-time only - they are erased when compiled to JavaScript and offer no runtime protection, unlike the # private field syntax
- Use JavaScript's native #privateField syntax instead of the private keyword when you need genuine runtime privacy, not just compile-time checking
Runtime & versions
Compiled to JavaScript. Feature availability depends on the language and runtime version used by your project; consult the official reference below.
TypeScript Handbook