Branded Type Runtime Validation
Create branded nominal types with runtime validation guards for type-safe data handling across module boundaries.
Code
export type Brand<T,B extends string> = T & { readonly __brand: B };export function brand<T,B extends string>(value:T,guard:(v:T)=>boolean,label:B):Brand<T,B>{if(!guard(value))throw new Error('invalid '+label);return value as Brand<T,B>;}export type Email=Brand<string,'Email'>;export type UserId=Brand<number,'UserId'>;export function isEmail(s:string):s is Email{return/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(s);}export function makeEmail(s:string):Email{if(!isEmail(s))throw new Error('invalid email');return s as Email;}How the snippet works
The working surface is the functions brand, isEmail and makeEmail — everything else is wiring.
Invalid states are rejected up front: it throws Error instead of continuing with bad data.
Using it
brand is what another module would consume; nothing else here is load-bearing for callers.
Interactive Tools for This Topic
JSON to Zod Schema ConverterInfer typed Zod z.object schemas from JSON payloads locally, supporting nested objects, merged array shapes, enums, nullable fields, and JSDoc comments.JSON Schema ValidatorValidate JSON data against a JSON Schema definition and get detailed error reports. Supports type checking, required fields, and common constraint validation.JSONL / NDJSON InspectorValidate NDJSON and JSON Lines line-by-line, pinpoint syntax errors by line number, analyze key frequencies and types, and export a pretty JSON array.Credit Card Brand DetectorIdentify the card network from a number's prefix and length, validate the Luhn checksum, and show a masked form and the issuer identification number.
FAQ
- What happens if the preconditions do not hold?
- It throws `Error` before any real work runs — handle it at the call site or let it propagate deliberately.
- Is anything beyond the standard library required?
- Nothing beyond the standard library — the snippet is dependency-free. The file defines `brand`, `isEmail`, `makeEmail` at load time.
Report a problem with this exampleOpens a pre-filled issue on GitHub.