Branding/opaque types to prevent unit mixups
Prevent unit/tag mixups by intersecting base types with phantom brand properties; construct via factory functions only.
Intro
Goal: Separate look-alike values at the type level. A plain number cannot tell meters from seconds; a brand marker can.
- Zero runtime overhead
- Safer APIs and refactors
- Create via factories only
Brand primitive units
Brand markers keep units apart at compile time; wrong argument order fails type-checking.
type Meter = number & { readonly __brand: "meter" }
type Second = number & { readonly __brand: "second" }
function meter(n: number): Meter { return n as Meter }
function second(n: number): Second { return n as Second }
const d = meter(100)
const t = second(9)
function speed(dist: Meter, time: Second) { return (dist as number) / (time as number) }
// speed(t, d) // compile error: brands do not matchAll lessons in this course
- Branding/opaque types to prevent unit mixups
- Tagged IDs and domain modeling patterns
- Domain modeling — aggregates, invariants & services