Codectionary / Developer documentation / TypeScript

Access Modifiers: public, private, protected

Access modifiers control visibility of class members. public (the default) is accessible from anywhere. private restricts access to within the declaring class only, not even subclasses. protected allows access within the class and its subclasses, but not from outside. These are compile-time only checks - true runtime privacy needs the # syntax instead.

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 - private

protected 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

At a glance

Purpose
Static types for JavaScript
File extension
.ts ยท .tsx
Runs in
Compiled to JavaScript
Usually used with
JavaScript and its ecosystem

Specifications & further reading

Related TypeScript documentation