← Back to TypeScript Course | Chapter 6: Classes | Lesson 3 of 9

Access Modifiers (public, private, protected)

Access modifiers control where class members can be accessed. TypeScript provides public, private, and protected modifiers to express different levels of visibility.

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

typescript
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

typescript
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

typescript
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

typescript
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

typescript
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);

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.