Access Modifier (TypeScript)

Access modifiers — `public`, `private`, and `protected` — control where a class member can be used. They keep some fields and methods internal to a class instead of exposing everything.

TypeScript

By default class members are `public` (usable anywhere). `private` limits a member to inside the class, and `protected` allows the class and its subclasses. These are compile-time checks in TypeScript.

TypeScript also offers a parameter-property shorthand: writing a modifier directly on a constructor parameter declares and assigns the field in one step, cutting boilerplate.

Syntax

private name: type;

Examples

TypeScript — Compile error: Property 'balance' is private and only accessible within class 'BankAccount'.

class BankAccount {
  private balance = 0;
  deposit(amount: number) {
    this.balance += amount;
  }
}

const a = new BankAccount();
a.balance;

Learn it in a lesson

See also

Back to the Dictionary