Skip to content
dreamcode
dreamcode
Map
Branded types
Lesson 25 of 26
+15 XP on finish
TS EXPERTChapter 4 · TS Expert

Branded Types

A user id and an order id are both strings, so TypeScript happily lets you pass one where the other belongs. A branded type adds an invisible tag, string & { readonly __brand: "UserId" }, so the two no longer mix. Branded values are created only through a small function that validates and casts, which makes that function the single gate every value must pass through.

Worked example

How it reads

  • loadUser(order) would be a compile error: an OrderId is not a UserId
  • userId checks the format before branding
  • At run time a branded id is just a string
Cloud tip: Brand units too: meters and feet, cents and dollars. Mixed units have crashed real spacecraft.
index.ts
TYPESCRIPT
type-checked, then run in your browser
Console
Run your code to see its output here.
YOUR TURN

Brand Meters and Feet so passing feet to climb becomes a type error. Add feet(n: number) to create Feet and toMeters(ft: Feet): Meters (multiply by 0.3048 and round). Log climb(toMeters(feet(300))): climbed 91 m.

Press Run to check your work.