intermediate

Access modifiers

Use public, protected, private, readonly, and ECMAScript private fields to express API intent while remembering which checks exist only at compile time.

TypeScript offers `public`, `protected`, `private`, `readonly`, and ECMAScript `#private` fields. `private`/`protected` erase at compile time—runtime JS can still access minified properties. `#field` is true runtime privacy.

Use modifiers to document API intent and catch misuse at build time; do not treat TS private as a security boundary.

On interviews: explain difference between `private` and `#secret` and when `readonly` helps immutability.

Common pitfalls: relying on private for secrets, protected sprawl inviting subclass coupling, and fighting the type checker with `as any`.

The trade-off is compile-time ergonomics versus no runtime enforcement for classic modifiers.

Checklist:

  • Prefer `#field` when runtime privacy matters.
  • Mark API surface `public` intentionally.
  • Use `readonly` for shallow immutability hints.