bhylu.com

Advertisements

TypeScript Access Modifiers

public, protected and private restrict access through TypeScript’s checker. JavaScript #private fields additionally enforce private access at runtime; the two mechanisms are not interchangeable.

How it works

A collection drawer keeps its receipt token inside a # field. Only the display method exposes a deliberately shortened value. This is encapsulation, not encryption: source code, logs or a compromised process can still reveal sensitive information elsewhere. Protected members are accessible to subclasses and should not become an accidental back door around an invariant.

Run the code

Try in playground loads this source without running it. Choose Run when ready. The existing TypeScript 5.8.3 worker transpiles and executes one file; it does not perform full semantic type checking, load npm imports or provide DOM/Node APIs. Use the local compiler for the type contract.

For a full check, save the three downloads together in a new folder, run npm install, then npm run check. Use npm run build followed by npm start to execute the checked JavaScript with Node. The supplied project enables strict checking, indexed-access checks and exact optional properties.

Example

lesson.ts

class CollectionDrawer {
  #token: string;
  constructor(token: string) { this.#token = token; }
  public hint(): string { return this.#token.slice(-3); }
}
const drawer = new CollectionDrawer("demo-receipt-482");
console.log(drawer.hint());

Expected result

482

The object exposes a hint rather than the whole token. Private fields require a runtime target or transpilation support; the pinned compiler emits a supported form for the existing browser runner. A TypeScript private property does not provide the same JavaScript runtime boundary as #token.