Course contentsShow
← TypeScript
Lesson 1036 of 1,79624. Classes in TypeScriptFree lesson

Private Fields with # Syntax

Using ECMAScript private fields (#field) for true runtime privacy that JavaScript engines enforce.

Private Fields with # Syntax

What you'll learn: How to use JavaScript's native # syntax for true runtime privacy that's enforced by the JavaScript engine itself, not just TypeScript's compiler.

The True Privacy Problem

You've learned about TypeScript's private modifier, but it has a significant limitation: it only exists at compile-time. Once your code compiles to JavaScript, those private members become completely accessible. Anyone can access them at runtime.

ECMAScript private fields solve this with the # prefix syntax. These are real private fields that JavaScript engines enforce at runtime. They're truly inaccessible from outside the class.

Basic Syntax

Private fields start with a # symbol and must be declared in the class body:

class BankAccount {
  #balance: number;

  constructor(initialBalance: number) {
    this.#balance = initialBalance;
  }

  getBalance(): number {
    return this.#balance;
  }

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

const account = new BankAccount(1000);
account.deposit(500);
console.log(account.getBalance()); // 1500
// account.#balance; // SyntaxError at RUNTIME

TypeScript's private vs JavaScript's #

Unlike private, which TypeScript strips away during compilation, #balance becomes real JavaScript that the engine protects. Even in the compiled output, the # remains, and any attempt to access it from outside throws a runtime error.

Think of private as a "please don't touch" sign that disappears when the code runs, while # is a locked door that stays locked forever.

When to Use Each

Use # when you need genuine runtime privacy — protecting sensitive data or internal state that must never be accessible. Use private when you just want compile-time guidance for your team without the slight syntax overhead.

Key Takeaway: Private fields with # provide true, runtime-enforced privacy that survives compilation, making them the only way to guarantee encapsulation in both TypeScript and JavaScript environments.