typescript / intermediate
Snippet
Protecting Object Properties with Private Identifiers and Accessors
JavaScript ECMAScript private fields marked with `#` offer true runtime privacy compared to TypeScript's `private` keyword compile-time modifier, preventing unauthorized external access even after compilation.
snippet.ts
typescript
1
2
3
4
5
6
7
8
9
10
11
12
13
14
class SecureTokenStore {#secretKey: string;constructor(key: string) {this.#secretKey = key;}public validate(candidate: string): boolean {return this.#secretKey === candidate;}}const store = new SecureTokenStore("super-secret-123");console.log(store.validate("wrong-key"));
Breakdown
1
#secretKey: string;
Declares a hard private field enforced at runtime by the JS engine, inaccessible outside the class declaration.
2
return this.#secretKey === candidate;
Accesses the internal secret key safely inside a public class method.