Branded Type
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."
Related Terms
Nominal Typing
Nominal typing is the VIP list at a club — even if you look exactly like someone on the list, you can't get in unless your name matches.
Type Guard
A type guard is like a bouncer at a club checking IDs. Before your code enters the VIP section, the guard checks 'are you a string or a number?
TypeScript
TypeScript is JavaScript with a strict parent watching over it.
Utility Types
Utility types are TypeScript's built-in type transformers — like Instagram filters but for your interfaces.