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;}Report a problem with this exampleOpens a pre-filled issue on GitHub.