typescript / intermediate
Snippet
Type-Safe Input Sanitization via Branded Types
Branded types create nominal type distinctions over primitive types like strings. This forces developers to pass user input through an explicit sanitization function before it can be accepted by security-sensitive rendering functions.
snippet.ts
typescript
1
2
3
4
5
6
7
8
9
10
11
12
13
14
type SanitizedString = string & { readonly __brand: unique symbol };function sanitizeInput(raw: string): SanitizedString {const sanitized = raw.replace(/<[^>]*>/g, "").trim();return sanitized as SanitizedString;}function renderContent(safeContent: SanitizedString): string {return `<article>${safeContent}</article>`;}const userInput = "<script>alert('xss')</script> Hello World ";const safeText = sanitizeInput(userInput);const htmlOutput = renderContent(safeText);
Breakdown
1
type SanitizedString = string & { readonly __brand: unique symbol };
Defines a branded type that is structurally a string at runtime but distinct to the TypeScript compiler.
2
return sanitized as SanitizedString;
Uses a type assertion within the validator function to mark the cleaned string as safe.
3
function renderContent(safeContent: SanitizedString): string {
Restricts the parameter to only accept strings that have explicitly passed through validation.
4
const htmlOutput = renderContent(safeText);
Successfully invokes renderContent because safeText has been properly validated and branded.