Branded types and nominal typing
Why two string IDs are interchangeable in TypeScript, and how a brand makes UserId and OrderId distinct types with no runtime cost.
Structural typing and excess property checksExtending interfaces and intersection typesType guards and assertion functionsType assertions, non-null, and satisfies
Branded types and nominal typing
The player loads from youtube-nocookie.com when you press play. Nothing reaches YouTube before that.
Not started
What you'll learn
- TypeScript compares types by shape, so two aliases of `string` such as `UserId` and `OrderId` are the same type, and swapping them is never an error.
- A brand intersects the base type with a property that exists only in the type system, like `string & { readonly [brand]: "UserId" }`, and two different brand names make the types incompatible.
- Brands cost nothing at runtime: the value is still a plain string or number, and the brand property is never created.
- A plain value can only become branded through a cast, so put that cast inside one function per brand that checks the value first, and use that function everywhere else.
- A type guard or assertion function returning `value is Email` lets a check brand a value without a separate cast at the call site.
- Branded values still work wherever the base type is accepted, but arithmetic and string methods return the plain base type, so the brand doesn't survive transformations.
Two IDs that are secretly the same
Most apps have a lot of IDs, and they’re usually all strings. Giving them names feels like it should help:
type UserId = string;
type OrderId = string;
function cancelOrder(orderId: OrderId) { /* ... */ }
const userId: UserId = "u_123";
cancelOrder(userId); // compiles
That call compiles, and in production it cancels nothing or, worse, the wrong thing. A type alias is just a second name for string. As the lesson on structural typing explains, TypeScript compares types by what they contain, and a UserId contains exactly what an OrderId contains.
Languages like Java and C# work the other way: two classes with identical fields are still different types because they have different names. That’s nominal typing. TypeScript doesn’t have it, but you can get the part you need.
Adding a brand
The trick is to give each type something the other lacks, using an intersection with a property that only exists on paper:
declare const brand: unique symbol;
type Brand<T, Name extends string> = T & { readonly [brand]: Name };
type UserId = Brand<string, "UserId">;
type OrderId = Brand<string, "OrderId">;
declare function cancelOrder(orderId: OrderId): void;
declare const userId: UserId;
cancelOrder(userId);
// error TS2345: Argument of type 'UserId' is not assignable to parameter of type 'OrderId'.
// Type 'UserId' is not assignable to type '{ readonly [brand]: "OrderId"; }'.
// Types of property '[brand]' are incompatible.
// Type '"UserId"' is not assignable to type '"OrderId"'.
cancelOrder("o_456");
// error: Argument of type 'string' is not assignable to parameter of type 'OrderId'.
The two types now differ in one property, whose types are the literals "UserId" and "OrderId". A raw string fails too, because it has no brand at all.
The declare const brand: unique symbol line declares a symbol that exists only for the checker. Using it as the key means no real object can accidentally have the property, since no code can ever get hold of that symbol to write it. You’ll also see the older form string & { __brand: "UserId" }, which works the same way with a plain string key.
Think of it like the stamp on a ticket. The paper is the same as any other sheet; the stamp says which event it’s for, and the door staff check the stamp, not the paper.
Zero cost at runtime
Nothing in the brand produces JavaScript. The property is never created, and unique symbol is only declared. A UserId is a string in memory, it serializes to JSON as a string, and every string method works on it:
declare const id: UserId;
id.length; // number
id.startsWith("u_"); // fine: a UserId is still a string
That’s the main difference from wrapping each ID in a class. A wrapper gives you real nominal checks (a class with a private field is only compatible with itself), but every value becomes an object you have to unwrap at every boundary.
Getting a branded value
A plain string can never satisfy the brand on its own, so somewhere you need a type assertion. The discipline is to write it once, behind a check:
function toUserId(raw: string): UserId {
if (!/^u_\d+$/.test(raw)) {
throw new Error(`Not a user ID: ${raw}`);
}
return raw as UserId;
}
This is sometimes called a smart constructor. If toUserId is the only place in the codebase that writes as UserId, every UserId in the program has passed the check, and the type carries that fact forward to code that never sees the check.
Type guards and assertion functions fit the same job when you’d rather narrow than return a new value:
type Email = Brand<string, "Email">;
function assertEmail(value: string): asserts value is Email {
if (!/^[^@\s]+@[^@\s]+$/.test(value)) {
throw new Error("Invalid email address");
}
}
declare function sendWelcome(to: Email): void;
function signUp(input: string) {
assertEmail(input);
sendWelcome(input); // input: Email
}
Now sendWelcome can’t be called with an unchecked string. That’s the bigger benefit of brands: they record that validation happened, not just which kind of ID something is. Schema libraries have this built in; Zod’s .brand<"Email">() produces a branded output type from a schema, which the runtime validation lesson builds on.
Where brands fall off
A branded value is still assignable to its base type, so it passes into any function expecting string or number. Going through an operation loses the brand:
type Cents = Brand<number, "Cents">;
const price = 1999 as Cents;
const doubled = price * 2; // number, not Cents
const total: Cents = doubled;
// error: Type 'number' is not assignable to type 'Cents'.
That’s the right behavior. The checker can’t know that doubling a valid price gives a valid price, so it asks you to send the result back through the function that makes Cents. The same applies to toUpperCase() on a branded string.
Use brands where a mix-up is costly and easy to make: IDs from different tables, money in different units, strings that must be sanitized before use. Branding every string in a codebase adds casts and friction for little gain.
About the video
The Typed Rocks video walks the same path in eleven minutes: the problem structural typing causes for primitives, the brand intersection pattern, and assertion functions as the way to create branded values. It uses plain TypeScript with no libraries. Lucas Barake’s video in the links shows the same motivation, then moves to runtime-enforced brands with the Effect library, which is useful once the plain pattern is clear.
Check yourself
Why does passing a `UserId` to a function expecting an `OrderId` compile when both are declared as `type UserId = string` and `type OrderId = string`?
A type alias only gives a new name to an existing type. Both names refer to `string`, and TypeScript's structural typing compares what types contain, not what they are called, so the two are identical.
How does `string & { readonly [brand]: "UserId" }` stop a `UserId` being used as an `OrderId`?
The `OrderId` version requires the brand property to have the literal type `"OrderId"`. A `UserId` has it as `"UserId"`, and those literal types don't match, so assignment fails. A plain `string` fails too, because it has no brand property at all.
What does a `UserId` look like at runtime?
It's an ordinary string. The brand property is declared only in the type, and the cast that creates a branded value emits no code, so there's no wrapper object and no extra memory.
Why is it a good idea to write the `as UserId` cast in exactly one place?
The cast is a claim the compiler accepts without checking. Keeping it inside a single function that validates the input first means every `UserId` in the program was checked once, and anywhere else, a cast stands out in review.
`const price = 1999 as Cents; const total = price * 2;` What is the type of `total`, and why?
It's `number`. Arithmetic on a branded number produces a plain `number`, because the operator knows nothing about brands. To keep the brand, pass the result back through the function that creates `Cents`.
Go deeper
Notes
Notes are saved to your account.
Everything else on this page works without one — progress and bookmarks keep themselves in this browser and come with you when you sign in. Notes are the one thing worth not trusting to a browser you might clear.
Your notes could not be loaded.