← blog
TypeScriptNovember 27, 2026 · 5 min read

TypeScript Can't Tell userId From orderId. Branded Types Can.

TypeScript's structural typing treats userId and orderId as the same type if both are `string` — branded types make them incompatible at compile time.

Parsa Jiravand · Frontend engineer · building bestpractic
TypeScript Can't Tell userId From orderId. Branded Types Can.

A support engineer is looking at a refund ticket. They copy an ID from one browser tab, paste it into another, and call issueRefund(id). The function signature says id: string. The ID they pasted is a string. TypeScript has nothing to say about it.

The refund goes out. Just not to the customer who filed the ticket — to whoever that ID actually belonged to.

Nobody wrote a bug here. The types were never wrong. That's the part that should bother you.

Here's the function, trimmed to the part that matters:

TypeScript
1
2
3
4
5
6
7
8
9
10
function issueRefund(userId: string, amountCents: number) { // looks up the user, credits their account } function getOrder(orderId: string) { // fetches the order } const order = getOrder("ord_9f21"); issueRefund(order.customerOrderId, 500); // ord_9f21, not a user id

That last line compiles clean. order.customerOrderId is a string. issueRefund wants a string. TypeScript checks shapes, not names — to the compiler, UserId and OrderId were never distinct in the first place, because nobody declared them. They're both just string, and every string is interchangeable with every other string.

This is structural typing, and 95% of the time it's exactly what you want — it's why you can pass a plain object literal anywhere an interface is expected without extending anything. The 5% is IDs, currency amounts, sanitized vs. raw HTML, and anything else where the shape is identical but the meaning isn't allowed to mix.

Spot where you'd make this mistake yourself? Rename the variables and it's not obvious at all — which is exactly why it ships.

The first instinct is a type alias:

TypeScript
1
2
3
4
5
6
7
type UserId = string; type OrderId = string; function issueRefund(userId: UserId, amountCents: number) { /* ... */ } const orderId: OrderId = "ord_9f21"; issueRefund(orderId, 500); // still compiles

Still compiles. A type alias doesn't create a new type — it creates a second name for the same type. UserId and OrderId both resolve to string, so as far as the checker is concerned you wrote issueRefund(id: string, ...) twice. The alias documents intent for a human skimming the code; it does nothing for the compiler.

Branded types close the gap by attaching a marker property that exists only in the type system — never at runtime:

TypeScript
1
2
3
4
5
6
7
8
9
10
11
12
13
14
type Brand<T, B extends string> = T & { readonly __brand: B }; type UserId = Brand<string, "UserId">; type OrderId = Brand<string, "OrderId">; function issueRefund(userId: UserId, amountCents: number) { /* ... */ } function toUserId(raw: string): UserId { return raw as UserId; } function toOrderId(raw: string): OrderId { return raw as OrderId; }

Now the swap is a compile error:

TypeScript
1
2
3
4
5
6
const orderId = toOrderId("ord_9f21"); issueRefund(orderId, 500); // Argument of type 'OrderId' is not assignable to parameter of type 'UserId'. // Type 'OrderId' is not assignable to type '{ readonly __brand: "UserId"; }'. // Types of property '__brand' are incompatible. // Type '"OrderId"' is not assignable to type '"UserId"'.

UserId and OrderId are both still strings underneath — __brand never appears in a compiled .js file, it's erased along with every other type annotation. It costs nothing at runtime and nothing in bundle size. All it does is give the structural checker something to disagree about, which is the entire point: you're opting one specific type out of structural compatibility.

The only place you're allowed to use as UserId is inside toUserId itself — a narrow, named boundary function. Every other call site just passes a UserId it already has, the same way you'd never cast to string by hand in normal code.

This is the honest caveat, and skipping it is how teams get a false sense of safety: a brand is a label, not a check. toUserId("literally anything") will happily mint a UserId out of a string that was never looked up anywhere. Branding stops a valid OrderId from sneaking into a UserId slot — it does nothing to stop an invalid string from becoming either one.

If you need the value validated too, put a real check inside the boundary function instead of a bare cast:

TypeScript
1
2
3
4
5
6
function toUserId(raw: string): UserId { if (!/^usr_[a-z0-9]+$/.test(raw)) { throw new Error(`not a valid user id: ${raw}`); } return raw as UserId; }

If you're already on a validation library, you likely don't need Brand<> yourself — Zod's .brand() does the same type-level trick and ties it to an actual runtime parse: z.string().brand<"UserId">() gives you a UserId only after the string has actually been validated. Reach for the hand-rolled version above when you're branding something you already trust (a value straight out of your own database row), and a validation library's version when the string is coming from outside — a request body, a query param, a pasted ID in a support ticket.

One type error at the call site instead of a wrong refund in production. No new runtime cost — the brand is erased at compile time like every other TypeScript annotation. No new dependency, if you don't want one. And it generalizes past IDs: money as Brand<number, "Cents"> so you can't add dollars to cents, Brand<string, "SanitizedHtml"> so raw user input can't reach dangerouslySetInnerHTML without passing through your sanitizer first, anywhere "same shape, different meaning" is the actual bug waiting to happen.

The support engineer in the opening scene didn't do anything wrong. The types just never told them userId and orderId were different promises. Now they do.

Runs right in your browser — poke at it and watch the concept react live.

Instant feedback, a hint on every question, and an explanation for each answer — right or wrong.

Where else in your codebase are two meanings hiding behind one primitive type? Money amounts in different currencies? Sanitized vs. raw strings? Drop the pair in the comments — I'll bet at least one of them has shipped a swap bug already.


🚀 Want more like this? Every guide, playground, and quiz lives on bestpractic.org — open it and sign up free so the next one finds you.

Thanks for reading! Let's stay connected:

Keep reading

One post a day, in your inbox

Each one with a runnable playground and a quiz. No pitch, no digest, unsubscribe in one click.

0 comments

Sign in to join the discussion, like comments, and save articles for later.