0Pricing
TypeScript Academy · Lesson

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 match

All lessons in this course

  1. Branding/opaque types to prevent unit mixups
  2. Tagged IDs and domain modeling patterns
  3. Domain modeling — aggregates, invariants & services
← Back to TypeScript Academy