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

Comparing private vs # Private Fields

Key differences between TypeScript's private and JavaScript's # including runtime behavior and visibility.

Comparing private vs # Private Fields

What you'll learn: You'll understand the key differences between TypeScript's private keyword and JavaScript's # private fields, including when each is actually enforced.

The Core Difference

TypeScript gives you two ways to make class members private, but they work at completely different times:

  • private — a TypeScript-only keyword that disappears after compilation. It provides compile-time safety but no runtime privacy.
  • # private fields — true JavaScript private fields that exist at runtime and provide actual encapsulation.

Think of private like a "do not enter" sign on a door—it warns you away during development, but the door isn't actually locked. The # syntax, on the other hand, is a real lock: the property simply doesn't exist outside the class at runtime.

Compile-Time vs Runtime Privacy

class WithPrivateKeyword {
  private secret = "visible at runtime";
}

class WithHashPrivate {
  #secret = "truly hidden";
}

const a = new WithPrivateKeyword();
const b = new WithHashPrivate();

// TypeScript error, but works at runtime:
// console.log(a.secret); // compiles to valid JS access

// TypeScript error AND runtime error:
// console.log(b.#secret); // syntax error in JavaScript

After compilation, private secret becomes a regular property—anyone with the JavaScript can access it. But #secret remains truly private in the JavaScript output.

Visibility in Compiled Code

The private keyword completely vanishes during compilation. The JavaScript output contains a normal property. With #, the private field syntax is preserved in the output (for modern targets) or transformed into WeakMaps for compatibility.

When to Use Each

Use private when you want TypeScript's type checking to prevent accidental access within your codebase, but don't need runtime enforcement.

Use # when you need true privacy guarantees—perhaps for security-sensitive data or when creating libraries where you want to guarantee internal state can't be tampered with.

Key Takeaway: TypeScript's private keyword only enforces privacy during development, while JavaScript's # private fields provide actual runtime encapsulation—choose based on whether you need compile-time guidance or runtime protection.