typescript / intermediate
Snippet
True Runtime Encapsulation with ECMAScript Private Fields
TypeScript's private modifier only performs static checks during compilation, leaving properties visible on runtime objects. Using native ECMAScript private fields prefixed with # guarantees true privacy at runtime in JavaScript engines.
snippet.ts
typescript
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
class BankAccount {#balance: number;public readonly accountId: string;constructor(accountId: string, initialDeposit: number) {this.accountId = accountId;this.#balance = initialDeposit;}public deposit(amount: number): void {if (amount <= 0) throw new Error("Deposit amount must be positive");this.#balance += amount;}public getBalance(): number {return this.#balance;}}
Breakdown
1
#balance: number;
Declares a hard private field using the hash prefix, making it inaccessible outside the class even at runtime.
2
this.#balance += amount;
Accesses and mutates the private field inside instance methods safely.