TypeScript ยท Chapter 24 of 44

TypeScript Access Modifiers

Access modifiers control which parts of your code can access a class's properties and methods. TypeScript supports `public`, `private`, and `protected`, giving you control over encapsulation.

By default, all class members are `public`, meaning they can be accessed from anywhere. Marking something `private` restricts access to inside the class only, while `protected` allows access in the class and its subclasses.

Syntax
class Account {
  private balance: number = 0;
  public owner: string;
}

public and private

`public` members (the default) can be accessed from anywhere. `private` members can only be accessed inside the class where they are defined, not from outside or from subclasses.

protected

`protected` members behave like private but are also accessible from subclasses, making them useful for values that subclasses need to use internally but outside code should not touch.

Example 1 (typescript)
class Account {
  private balance: number = 0;

  deposit(amount: number): void {
    this.balance += amount;
  }

  getBalance(): number {
    return this.balance;
  }
}
const acc = new Account();
acc.deposit(100);
console.log(acc.getBalance());
Output
100

balance is private, so it can only be changed through the class's own methods like deposit().

Example 2 (typescript)
class Animal {
  protected sound: string = "...";
  makeSound(): string {
    return this.sound;
  }
}
class Dog extends Animal {
  constructor() {
    super();
    this.sound = "Woof";
  }
}
console.log(new Dog().makeSound());
Output
Woof

sound is protected, so the Dog subclass can access and change it, but outside code cannot.

Key points

  • public members are accessible from anywhere (the default).
  • private members are only accessible inside the same class.
  • protected members are accessible in the class and its subclasses.
  • Access modifiers help enforce encapsulation and safer class design.
๐Ÿ’ก Note: These modifiers are checked only at compile time; they do not add true runtime privacy like some other languages.

๐Ÿ“ Quick Quiz

1. What is the default access modifier in TypeScript classes?

2. Where can a private member be accessed?

3. Which modifier allows access from subclasses but not from outside code?