Skip to content

Branded Type

Spicy — senior dev territoryGeneral Dev

ELI5 — The Vibe Check

A branded type is like putting a name tag on a string so TypeScript doesn't let you accidentally mix up a UserId with an Email, even though they're both just strings underneath. It's type-level trust issues, and that's a good thing.

Real Talk

A TypeScript pattern that creates nominally unique types from primitive types by intersecting them with a phantom brand property. This prevents accidental interchange of structurally identical types (like UserId and OrderId both being strings) without any runtime cost.

Show Me The Code

type Brand<T, B> = T & { __brand: B };

type UserId = Brand<string, 'UserId'>;
type OrderId = Brand<string, 'OrderId'>;

function getUser(id: UserId) { /* ... */ }

const userId = 'abc' as UserId;
const orderId = 'xyz' as OrderId;

getUser(userId);   // OK
// getUser(orderId); // Error! Type 'OrderId' is not assignable

When You'll Hear This

"We use branded types for all our IDs so you can't accidentally pass an OrderId where a UserId is expected." / "Branded types cost nothing at runtime but save you from a whole class of bugs."

Made with passive-aggressive love by manoga.digital. Powered by Claude.