typescript / expert
Snippet
Nominal Subtyping with Symbol-Based Private Key Encapsulation
By combining `unique symbol` property keys with class inheritance, TypeScript enforces nominal-like scope boundary safety for object state. Property names computed with unique symbols cannot be accessed by external classes without direct reference to the exact symbol instance, creating zero-leak private members across OOP class hierarchies.
snippet.ts
typescript
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
const SecretKey: unique symbol = Symbol("SecretKey");export abstract class SecureEntity {private readonly [SecretKey]: string;constructor(secret: string) {this[SecretKey] = secret;}protected getSecret(this: SecureEntity): string {return this[SecretKey];}}export class UserSession extends SecureEntity {public validateToken(input: string): boolean {return this.getSecret() === input;}}
Breakdown
1
const SecretKey: unique symbol = Symbol("SecretKey");
Declares a unique symbol type that exists uniquely in the type registry for object keying.
2
private readonly [SecretKey]: string;
Defines an un-enumerable, symbol-keyed private property within the base entity class.
3
protected getSecret(this: SecureEntity): string
Provides controlled subclass access while restricting execution scope via explicit 'this' typing.