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 UserIduserIdchecks 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.


