Access Modifiers (public, private, protected)
In this page:
Public Members
Public members can be accessed from anywhere the object itself is accessible, and public is the default visibility in TypeScript classes when no modifier is written at all.
Example: Public Members
class Person {
public name: string = "Guest"; // public is also the default
}
const p = new Person();
console.log(p.name);
Private Members
Private members can only be accessed within the class that declares them, which is useful for hiding implementation details like internal caches or helper state that outside code should never touch directly.
Example: Private Members
class BankAccount {
private balance: number = 0;
deposit(amount: number) {
this.balance += amount;
}
getBalance() {
return this.balance;
}
}
const acc = new BankAccount();
acc.deposit(100);
console.log(acc.getBalance());
Protected Members
Protected members can be accessed inside the declaring class and inside classes that inherit from it, striking a middle ground that's useful for values a subclass needs to build on but that outside callers shouldn't see.
Example: Protected Members
class Animal {
protected sound: string = "...";
}
class Dog extends Animal {
bark() {
console.log(this.sound);
}
}
new Dog().bark();
Combining Modifiers
A class can mix different access modifiers across its members, exposing a small public API while keeping the supporting fields and helper methods private or protected, which is the essence of encapsulation.
Example: Combining Modifiers
class User {
public name: string;
private password: string;
protected role: string;
constructor(name: string, password: string, role: string) {
this.name = name;
this.password = password;
this.role = role;
}
}
const u = new User("Sam", "secret", "admin");
console.log(u.name);
Choosing the Right Modifier
Use public for values that form part of the object's accessible interface, private for implementation details no other code should depend on, and protected for anything a future subclass is expected to extend or override.
Example: Choosing the Right Modifier
class Order {
public id: number; // part of the public interface
private total: number; // implementation detail
protected status: string; // usable by subclasses
constructor(id: number, total: number, status: string) {
this.id = id;
this.total = total;
this.status = status;
}
}
console.log(new Order(1, 50, "pending").id);
Chapter Quiz — Complete all 9 topics to unlock
0/9 topics done
Complete these topics first: