QA
Intermediate LevelJavaScript & TypeScript

How do private class fields (#field) in ES2022 differ from TypeScript private access modifiers?

❓ Interview Prompt: Compare hard runtime privacy (#field) with soft compile-time TS privacy (private modifier).

JavaScript and TypeScript offer two different mechanisms for private class members:

1. TypeScript private Modifier:

•
Compile-Time Privacy ONLY: Erased completely when compiled to JavaScript.
•
Can still be accessed at runtime in JS or via bracket notation (obj['privateProp']).

2. ES2022 Hard Private Fields (#field):

•
Hard Runtime Encapsulation: Enforced directly by the JS engine (V8).
•
Accessing #field from outside the class throws a syntax error at runtime. Cannot be bypassed even with bracket notation or reflection!

Code Implementation Example

javascript
class BankAccount {
  private tsPrivate = 'Compile-time only'; // TS private
  #hardPrivate = 'Runtime enforced';      // ES hard private

  getSecret() {
    return this.#hardPrivate; // Allowed inside class
  }
}

const account = new BankAccount();
// console.log(account.#hardPrivate); // ❌ SyntaxError: Private field '#hardPrivate' must be declared in an enclosing class

// TS private can still be accessed at JS runtime!
console.log(account['tsPrivate']); // "Compile-time only" (Not safe at runtime!)
💡Hard runtime privacy of ES2022 #fields vs soft compile-time TypeScript private modifier.
🎯 Interview Key Takeaway

Use ES #private fields when hard runtime encapsulation is required. Use TS private for lightweight compile-time contracts.

#Private Fields#Classes#ES2022#Intermediate
Back to all JavaScript & TypeScript Questions→

More JavaScript & TypeScript Interview Questions

Beginner LevelJavaScript & TypeScript

What are the differences between var, let, and const in JavaScript?

Beginner LevelJavaScript & TypeScript

What are the JavaScript data types and the difference between primitives and objects?

Beginner LevelJavaScript & TypeScript

What is the difference between == (loose equality) and === (strict equality)?