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.
class Wallet { private balance = 0; // checked by the compiler only #pin = "1234"; // enforced by JavaScript }
Try it
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.
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
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
#xon an object that lacks it throws aTypeErrorat runtime. #privatenames cannot be declared in interfaces, object literals or with accessibility keywords.
Usage notes
privatemembers still count for type compatibility: two classes with private members of the same name from different declarations are not assignable to each other.#privateis 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
#privatefields, butconsole.logof the instance in Node does not show them by default. - Use
protectedwhen subclasses need access;#privatecannot be shared with them.