typescript / expert
Snippet
Opaque Branded Auth Tokens with Type-Level Privileged Access Guarding
Nominal branding attaches invisible type tags using a non-existent unique symbol key to primitive types like `string`. This prevents structural equivalence from allowing unvetted string tokens into privileged domain functions, enforcing authorization flows directly through the type-checker.
snippet.ts
typescript
1
2
3
4
5
6
7
8
9
10
11
12
13
14
declare const BrandSymbol: unique symbol;type Brand<T, B extends string> = T & { readonly [BrandSymbol]: B };type UnauthenticatedToken = Brand<string, "UNAUTH">;type AdminToken = Brand<string, "ADMIN">;function elevateToken(token: UnauthenticatedToken, secret: string): AdminToken {if (secret !== "SUPER_SECRET") throw new Error("Unauthorized");return token as unknown as AdminToken;}function executeAdminAction(token: AdminToken, command: string): void {console.log(`Executing ${command} with token ${token}`);}
Breakdown
1
type Brand<T, B extends string> = T & { readonly [BrandSymbol]: B };
Constructs an opaque nominal type by intersection of base type T with a unique symbol brand object.
2
function elevateToken(token: UnauthenticatedToken, secret: string): AdminToken
Exposes an explicit verification boundary that elevates an unprivileged token into a branded AdminToken.
3
function executeAdminAction(token: AdminToken, command: string): void
Rejects raw string arguments at compile time, accepting only verified AdminToken branded instances.