typescript / intermediate
Snippet
Enforcing Security Boundaries with Branded String Types
Branded types create nominal type safety over structural string primitives. This compile-time check prevents passing unvalidated raw strings into security-critical operations.
snippet.ts
typescript
1
2
3
4
5
6
7
8
9
10
11
12
13
declare const brand: unique symbol;type Branded<T, B> = T & { [brand]: B };type SanitizedHtml = Branded<string, "SanitizedHtml">;function sanitizeInput(rawInput: string): SanitizedHtml {const escaped = rawInput.replace(/</g, "<").replace(/>/g, ">");return escaped as SanitizedHtml;}function renderComponent(html: SanitizedHtml): void {// Safe to render without XSS vulnerability risk}
Breakdown
1
declare const brand: unique symbol;
Declares a unique symbol used to construct nominal branding tags without runtime overhead.
2
type Branded<T, B> = T & { [brand]: B };
Creates an intersection type attaching a nominal tag to a base type.
3
function sanitizeInput(rawInput: string): SanitizedHtml {
Sanitizes untrusted input strings and asserts the branded return type.
4
function renderComponent(html: SanitizedHtml): void {
Restricts parameters strictly to pre-sanitized strings, preventing raw string bugs.