Advertisement
Beginner TypeScript, Classes: Access Modifiers, Abstract Classes & Implements

How does the '#' private field syntax differ from the 'private' keyword?

Short answer

The 'private' keyword is a TypeScript-only, compile-time restriction — it's erased at compile time and the field is still a regular accessible property in the emitted JavaScript.

Save TypeScript mock interview
Advertisement
AModel answer
The 'private' keyword is a TypeScript-only, compile-time restriction — it's erased at compile time and the field is still a regular accessible property in the emitted JavaScript. The '#' syntax is real, native JavaScript privacy enforced at runtime, invisible and inaccessible even via bracket notation or reflection.
class Account {
  private tsPrivate = 1;   // compile-time only, visible in emitted JS
  #truePrivate = 2;        // enforced at runtime, invisible outside the class
}
Real-world example
Choosing '#' private fields when you need guaranteed runtime encapsulation, such as protecting sensitive internal state from any external access.
Likely follow-ups
  • Does '#' private syntax work in TypeScript targets older than ES2022?
Related topics