Access modifiers

Topic 2 of 3 in Classes7 min readIntermediateFree course

Overview

A class is more than a bag of properties: its methods keep its data valid. A bank account’s balance should only change through deposit and withdraw, which check the amounts. Access modifiers let you say which members are part of the public API and which are internal, so the type checker stops other code from reaching around the rules.

Who can see a member? public (the default): inside the class, subclasses and outside code can all use it. protected: inside the class and subclasses, not outside — enforced at compile time. private: only inside the class — enforced at compile time. #field: only inside the class — enforced at run time too. private is a TypeScript check only — the property still exists in the JavaScript output. JavaScript #private fields are truly hidden at run time. readonly can be combined with any of them.

public

Members are public by default; writing public is optional and mostly used for emphasis:

TypeScript
class Greeter {
  public greet(name: string) {
    return `Hello, ${name}`;
  }
}

private

A private member can only be used inside the class body:

TypeScript
class BankAccount {
  private balance = 0;

  deposit(amount: number) {
    if (amount <= 0) throw new RangeError("Deposit must be positive");
    this.balance += amount;     // ✓ inside the class
  }
}

const acc = new BankAccount();
acc.balance = 1_000_000;
// error TS2341: Property 'balance' is private and only accessible within class 'BankAccount'.

protected

A protected member is visible inside the class and its subclasses, but not outside:

TypeScript
class Shape {
  protected describeSize(size: number): string {
    return size > 100 ? "large" : "small";
  }
}

class Square extends Shape {
  side = 12;
  describe() {
    return `a ${this.describeSize(this.side ** 2)} square`;   // ✓ subclass
  }
}

new Square().describeSize(4);
// error TS2445: Property 'describeSize' is protected and only accessible within class 'Shape' and its subclasses.

Use protected for helpers that subclasses need but outside code shouldn’t call.

Compile time vs run time

Here’s the catch: private and protected are TypeScript features. They’re checked, then erased like all types. In the JavaScript output, balance is an ordinary property, and anyone can reach it:

TypeScript
(acc as any).balance = 1_000_000;    // compiles (any switches off checking) and works at run time
console.log(acc);                    // BankAccount { balance: 1000000 } — and it shows up in logs

For most application code, that’s fine: the type checker stops accidental misuse, which is what you want. When data must be truly hidden — security-sensitive values, library internals — use JavaScript’s own private fields.

#private fields

Names starting with # are private at run time, enforced by the JavaScript engine itself:

TypeScript
class BankAccount {
  #balance = 0;

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

  get balance() {
    return this.#balance;
  }
}

const acc = new BankAccount();
acc.#balance;
// error TS18013: Property '#balance' is not accessible outside class 'BankAccount' because it has a private identifier.

Even at run time, #balance can’t be read from outside, doesn’t appear in Object.keys, and isn’t printed by most loggers. Subclasses can’t see it either — there’s no #protected.

private x #x
Checked by TypeScript yes yes
Hidden at run time no yes
Visible in subclasses no no
Escape with as any yes no
Works with type stripping yes yes

Many teams now default to # for genuinely private state and use private mostly for methods. Either is fine; be consistent.

readonly

readonly stops a field from being reassigned after the constructor finishes:

TypeScript
class Order {
  readonly id: string;
  readonly createdAt = new Date();

  constructor(id: string) {
    this.id = id;                  // ✓ allowed in the constructor
  }

  rename() {
    this.id = "new";
    // error TS2540: Cannot assign to 'id' because it is a read-only property.
  }
}

Combine it with visibility: private readonly cache = new Map() — the reference never changes, though the Map’s contents can.

Getters for read-only views

A common pattern: keep the data private, expose a getter. Outside code can read the value but only change it through methods that enforce the rules:

TypeScript
class Counter {
  #count = 0;
  get count() { return this.#count; }
  increment() { this.#count++; }
}

const c = new Counter();
c.count;        // ✓ read
c.count = 5;
// error TS2540: Cannot assign to 'count' because it is a read-only property.

Designing the public surface

  • Start with everything private (or #), and make members public only when outside code needs them.
  • Expose operations (deposit, withdraw), not raw data that must stay consistent.
  • Return copies of internal arrays and objects ([...this.history]) so callers can’t modify them behind your back.
  • Use protected sparingly — every protected member is part of the contract with subclasses.

Remember: public for the API, protected for subclasses, private for internals (checked at compile time), #private when it must be hidden at run time too, and readonly for values set once.

Exercise

A protected bank account

Write class BankAccount with: a readonly id (string); a JavaScript private field #balance (number, starting at 0); a protected method record(entry: string) that adds to a private history array; public methods deposit(amount) and withdraw(amount) (throw a RangeError for non-positive amounts or insufficient funds) that both call record; a public getter balance; and a public statement(): string[] returning a copy of the history. Then write SavingsAccount extends BankAccount with a readonly rate and an addInterest() method that deposits interest and calls the protected record. Exercise them and print the balance and statement. Show with // @ts-expect-error that outside code can’t call record, can’t write balance, and can’t reassign id.

TypeScript
class BankAccount {
  // readonly id, #balance, private history, protected record(),
  // deposit(), withdraw(), get balance(), statement()
}

class SavingsAccount extends BankAccount {
  // readonly rate, addInterest()
}

Summary

  • public (the default) members are usable anywhere; protected ones inside the class and its subclasses; private ones only inside the class.
  • TypeScript’s private and protected are compile-time checks — the properties still exist at run time.
  • JavaScript #private fields are truly hidden at run time, and TypeScript types them too.
  • readonly stops reassignment after the constructor; combine it with any visibility.
  • Keep the public surface small: expose methods that keep the object valid, hide the data they protect.