Skip to content
Tutorials Center
My learning

Topics

TypeScript Reference ยท Classes, Enums and Decorators

TypeScript private versus #private fields

Reference for TypeScript class privacy: the private keyword (compile-time only) versus ECMAScript #private fields (enforced at runtime), with trade-offs.

TypeScript gives you two ways to hide class members. The private keyword is a compile-time check: the property still exists on the object and can be read at runtime. A name that starts with # (a private field) is part of JavaScript itself, and the engine refuses all access from outside the class body.

Choose private for ordinary encapsulation inside TypeScript code, and #name when privacy must hold at runtime, for example in a library whose users might not use TypeScript.

TypeScript
class Wallet {
  private balance = 0;   // checked by the compiler only
  #pin = "1234";         // enforced by JavaScript
}

Try it

TypeScript What each one allows

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

TypeScript Brand checks and subclasses

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

Syntax

TypeScript
class C {
  private a = 1;
  protected b = 2;
  #c = 3;
  #method() {}
  static #count = 0;
  has(o: object) { return #c in o; }
}
Feature private #private
Checked Compile time only Compile time and runtime
Visible in Object.keys, JSON.stringify Yes No
Accessible via obj["name"] Yes (escape hatch) No
Subclass can reuse the name No (error) Yes, separate slot
Works on methods, accessors, statics Yes Yes
Requires Any target ES2015+ target (natively ES2022)

Edge cases:

  • #x in obj (TypeScript 4.5+) tests whether an object has the private field, which makes a reliable brand check.
  • Reading #x on an object that lacks it throws a TypeError at runtime.
  • #private names cannot be declared in interfaces, object literals or with accessibility keywords.

Usage notes

  • private members still count for type compatibility: two classes with private members of the same name from different declarations are not assignable to each other.
  • #private is slower to downlevel (WeakMap helpers) for targets below ES2022; modern targets use the native feature.
  • Neither form hides data from a determined attacker running in the same process. They are encapsulation tools, not security boundaries.
  • Debuggers show #private fields, but console.log of the instance in Node does not show them by default.
  • Use protected when subclasses need access; #private cannot be shared with them.