typescript / expert
Snippet
Type-Safe Private State Access Control using WeakMap Closures
This snippet provides strong object encapsulation in TypeScript by combining module-scoped WeakMaps with frozen interfaces. It prevents external runtime inspection or state tampering while offering strict static typing and clean garbage collection semantics.
snippet.ts
typescript
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
interface UserPrivileges {readonly roles: string[];}const privateStore = new WeakMap<object, UserPrivileges>();export class AccountGuard {constructor(roles: string[]) {privateStore.set(this, { roles: Object.freeze([...roles]) });}public hasRole(role: string): boolean {const state = privateStore.get(this);return state ? state.roles.includes(role) : false;}}
Breakdown
1
interface UserPrivileges { readonly roles: string[]; }
Defines an immutable shape contract for internal instance data.
2
const privateStore = new WeakMap<object, UserPrivileges>();
Creates a WeakMap memory store inaccessible outside the module scope.
3
privateStore.set(this, { roles: Object.freeze([...roles]) });
Associates instance private state with deep runtime immutability.
4
public hasRole(role: string): boolean {
Provides controlled, type-safe public accessor method for internal checks.
5
const state = privateStore.get(this);
Retrieves private state linked strictly to the current instance context.