Branded Types
A branded type is a type alias intersected with a unique phantom property so the compiler will not mix it with the underlying type. UserId and OrderId can both be strings at runtime and stay distinct in TypeScript.
Detailed Explanation
type UserId = string is a nickname. Any string is a UserId. Passing an order id where a user id is expected compiles. That is structural typing doing its job, and it is the wrong job for identifiers, tokens, and units.
A brand adds a property that only exists in the type:
type UserId = string & { readonly __brand: "UserId" };
Nothing at runtime has __brand. You never read it. You produce a UserId through a constructor function that asserts the brand after it has checked the string. From then on, UserId is not assignable to OrderId, and a raw string is not assignable to either, unless you assert again.
This is an encoding of nominal typing. TypeScript does not have a nominal keyword. The phantom property is the usual encoding. Variants include a unique symbol key (typeof UserIdBrand) so the property name cannot collide, and a helper type Brand<T, B> = T & { readonly __brand: B }.
Brands are shallow and erased. JSON.stringify on a UserId produces a JSON string. A database driver will give you string. You re-apply the brand at the boundary after validation (parseUserId(raw: string): UserId). If you brand without validating, you have only renamed the assertion.
Where brands pay off: mixing ids (userId vs orderId), mixing units (Cents vs Dollars), mixing sanitized vs unsanitized strings (SafeHtml vs string). Where they do not: every alias in the program. A brand is friction. Put it on the values that, if mixed, cause a real incident.
Classes with private fields are a different nominal encoding: two classes with a private id are not assignable. Use a class when you already want an instance. Use a brand when the runtime value should stay a string or number.
Do not expose __brand in public docs as a real field. Do not rely on it in in checks; it is not there. The constructor function is the API.
Code Examples
1. Two branded ids that cannot be mixed.
// 1. Two branded ids that cannot be mixed.
type UserId = string & { readonly __brand: "UserId" };
type OrderId = string & { readonly __brand: "OrderId" };
function userId(raw: string): UserId {
if (raw.length === 0) throw new Error("empty id");
return raw as UserId;
}
function loadUser(id: UserId): void {
console.log(id);
}
const uid = userId("u1");
loadUser(uid);
// loadUser("u1");
// Error: string is not assignable to UserId.2. A reusable Brand helper.
// 2. A reusable Brand helper.
type Brand<T, B extends string> = T & { readonly __brand: B };
type Cents = Brand<number, "Cents">;
function cents(n: number): Cents {
if (!Number.isInteger(n) || n < 0) throw new Error("cents");
return n as Cents;
}
function formatUsd(value: Cents): string {
return (value / 100).toFixed(2);
}
console.log(formatUsd(cents(1999))); // 19.993. Symbol brand to avoid a string key collision.
// 3. Symbol brand to avoid a string key collision.
declare const orderBrand: unique symbol;
type OrderKey = string & { readonly [orderBrand]: void };
function orderKey(raw: string): OrderKey {
return raw as OrderKey;
}Common Gotchas
The brand is an assertion unless the constructor validates
`raw as UserId` without a check is `as` with extra typing. Put the rules in the function.
You cannot read `__brand` at runtime
it is not on the value. Do not write a type guard that checks for it.
Brands do not survive `JSON.parse`
the result is `string` or `unknown`. Parse, validate, then brand.
Branding every alias creates noise
save it for values that are dangerous to mix. `UserId` yes; `EmailString` maybe; `Name` usually no.