Skip to content

.tip

ยท one of the small things

Brand your ids so a UserId cannot be an OrderId

If two ids are both string, sooner or later someone swaps them in an argument list and the compiler says nothing.

type UserId = string & { readonly __brand: "UserId" };
type OrderId = string & { readonly __brand: "OrderId" };
const userId = (s: string) => s as UserId;

Now getOrder(userId) is a type error. It costs nothing at runtime and one line per id type, and it catches a kind of bug tests almost never do.

typescript