TypeScript Branded Types: Nominal Typing, Type Tags, and Validation
How a phantom property makes two strings incompatible, unique symbol brands, unit-typed numbers, and the places where a brand quietly disappears.

TypeScript's type system is structural: two types with the same shape are interchangeable, so type UserId = string and type OrderId = string are the same type and can be passed to each other's functions. A branded type breaks that equivalence by intersecting the underlying type with a property that exists only in the type system, making string & { __brand: "UserId" } a subtype of string that a plain string cannot satisfy. The result is nominal typing for the cases where mixing up two values of the same shape is a real bug, at the cost of one cast at the point where a value is validated.
Quick Summary
- A brand is an intersection with a phantom property:
type UserId = string & { readonly __brand: "UserId" }. - A branded value is assignable to its base type; the base type is not assignable to the brand, which is the whole point.
- Brands are erased at runtime; nothing validates, and
as UserIdon an unvalidated string compiles. - The safe constructor is a function that validates and returns the brand, so the cast lives in exactly one place.
- A
unique symbolkey is a stronger brand than a string key: it cannot collide with a real property and does not show up inkeyofas an ordinary name. - Brands survive object types (
Pick, property access) but disappear throughJSON.parse, spread into a wider type, and any index signature that accepts plain strings. - Units are the other natural use:
Meters,Seconds, andCentsas branded numbers prevent arithmetic across units that the compiler otherwise allows. - Error messages mention the brand, which turns "string is not assignable to string" into a message that names the mistake.
Basic syntax and type signatures
// String-keyed brand.
type UserId = string & { readonly __brand: "UserId" };
type OrderId = string & { readonly __brand: "OrderId" };
// Generic helper.
type Brand<T, B extends string> = T & { readonly __brand: B };
type Email = Brand<string, "Email">;
type Cents = Brand<number, "Cents">;
// Unique-symbol brand: the key cannot collide with a real property.
declare const brand: unique symbol;
type Brand2<T, B> = T & { readonly [brand]: B };
type Slug = Brand2<string, "Slug">;
// Object brand, when the value is a structure rather than a primitive.
type Post = { id: string; title: string } & { readonly __kind: "Post" };Constructors are the only place the cast is allowed to appear:
function toUserId(raw: string): UserId {
if (!/^[0-9a-f]{24}$/.test(raw)) throw new Error(`invalid user id: ${raw}`);
return raw as UserId; // one hop: string is assignable to the intersection
}
function toCents(amount: number): Cents {
if (!Number.isInteger(amount) || amount < 0) throw new Error("cents must be a non-negative integer");
return amount as Cents;
}
function isUserId(value: unknown): value is UserId {
return typeof value === "string" && /^[0-9a-f]{24}$/.test(value);
}The cast is legal in one hop because UserId is assignable to string, and the assertion rules accept a conversion when one direction holds. No double assertion through unknown is needed for a brand on a primitive, which keeps the constructor readable.
Comparison of nominal-typing techniques
| Technique | Prevents mixing same-shape values | Runtime cost | Survives JSON | Tooling clarity |
|---|---|---|---|---|
| Branded intersection | yes | none | no | error names the brand |
unique symbol brand | yes, and cannot collide | none | no | strongest of the type-only options |
| Wrapper class / record | yes | allocation | with serializers | needs mapping code |
| Enum of allowed values | only closed sets | object emit | yes | enum overhead |
| Runtime validation library (zod, io-ts) | yes | parse cost | yes | schema doubles as validator |
Nothing (plain string) | no | none | yes | zero |
Brands and validators solve different halves of the same problem: the validator proves a value is well-formed, and the brand carries that proof through the type system afterwards. Using only the brand means the proof can be fabricated with one as; using only the validator means the proof is forgotten the moment the value is assigned to a string.
Practical edge cases and deep dives
1. Two identifiers that share a shape
type UserId = Brand<string, "UserId">;
type OrderId = Brand<string, "OrderId">;
declare function getUser(id: UserId): Promise<{ id: UserId; name: string }>;
declare function getOrder(id: OrderId): Promise<{ id: OrderId; total: Cents }>;
declare const userId: UserId;
declare const orderId: OrderId;
getUser(userId); // ok
// getUser(orderId); // TS2345: Argument of type 'OrderId' is not assignable to parameter of type 'UserId'
declare const raw: string;
// getUser(raw); // TS2345: string is not assignable to UserId
getUser(toUserId(raw)); // validated
// The mistake this catches, written the way it usually happens:
const user = await getUser(orderId as unknown as UserId); // compiles; returns the wrong recordThe final line is the honest limit: a double assertion defeats any type-level scheme. What brands buy is that the mistake needs to be written explicitly, in one place, rather than happening silently because both parameters are string. In a codebase where ids are threaded through HTTP handlers, repositories, and cache keys, that difference is the difference between a type error and an order retrieved for the wrong customer.
2. Units, and arithmetic that respects them
type Meters = Brand<number, "Meters">;
type Feet = Brand<number, "Feet">;
type Seconds = Brand<number, "Seconds">;
const meters = (n: number): Meters => n as Meters;
const feet = (n: number): Feet => n as Feet;
const seconds = (n: number): Seconds => n as Seconds;
function addMeters(a: Meters, b: Meters): Meters {
return (a + b) as Meters; // the cast is the price of arithmetic
}
function speed(distance: Meters, time: Seconds): number {
return distance / time; // branded numbers are numbers for operators
}
const a = meters(100);
const b = meters(50);
addMeters(a, b);
// addMeters(a, feet(3)); // error: Feet is not Meters
// speed(meters(100), feet(3)); // error
const total: number = a + b; // widens silently: no brand on arithmetic resultsBranded numbers do not survive operators. a + b is number, and assigning it to a Meters parameter requires a cast, which is why every unit library that uses brands wraps the operations (add, scale, toFeet) rather than relying on +. The pattern is still worth it at the boundary: a function signature that takes Meters and Seconds cannot be called with a value that came from a Feet helper, and the conversion functions are the only places a factor appears.
3. unique symbol brands and why they are safer
// brand.ts
declare const brandSymbol: unique symbol;
export type Brand<T, B> = T & { readonly [brandSymbol]: B };
export type UserId = Brand<string, "UserId">;
export type Slug = Brand<string, "Slug">;A string-keyed brand adds a real-looking property name, which has two consequences. __brand becomes part of keyof UserId, so Object.keys, Pick, and spreading see it — and a serialized object can accidentally carry it, or a mapped type can preserve it in a place where it means nothing. A unique symbol key is invisible to every runtime operation and cannot be written in an object literal, so no value can acquire the brand by accident. The trade-off is that the symbol cannot appear in a JSON payload or a database column, but a brand should never be persisted anyway: store the validated base value, and brand it again on read.
// Reading a stored value: validate, then brand.
function loadUserId(row: { user_id: string }): UserId {
return toUserId(row.user_id);
}4. Where brands leak
type UserId = Brand<string, "UserId">;
type Users = Record<string, { name: string }>;
declare const id: UserId;
const users: Users = {};
users[id]; // ok: UserId is a string
// The brand disappears through the index signature.
const key: string = id;
users[key]; // also ok — the lookup never knew it was branded
// And through JSON.
const parsed = JSON.parse(JSON.stringify({ id })) as { id: UserId }; // no check happened
const roundTripped: UserId = JSON.parse(JSON.stringify(id)); // `any`, no error at all
// Spread into a wider type drops the brand from the object's fields.
type Row = { id: UserId; name: string };
const row: Row = { id, name: "x" };
const wide: { id: string; name: string } = row; // ok, brand widened on the way out
const back: Row = wide; // error: string is not UserIdTwo leaks matter in practice. JSON.parse returns any, so any assignment from it compiles regardless of the brand, and the type annotation on the receiving variable is a wish. Widening is the other: passing a branded value to a function that takes string is allowed, so the brand is lost as soon as the value crosses a helper with a less precise signature — and the value that comes back is a plain string. Keeping the branded type in the signatures of everything that handles ids is what keeps the guarantee, which is a real cost in a codebase with many small helpers.
5. Brands with maps, caches, and generic containers
type UserId = Brand<string, "UserId">;
type OrderId = Brand<string, "OrderId">;
const users = new Map<UserId, { name: string }>();
const orders = new Map<OrderId, { total: Cents }>();
declare const uid: UserId;
users.get(uid); // ok
// orders.get(uid); // error: UserId is not OrderId
// A cache keyed by a branded id in a generic container.
class Cache<K extends string, V> {
private map = new Map<K, V>();
get(key: K): V | undefined { return this.map.get(key); }
set(key: K, value: V): void { this.map.set(key, value); }
}
const userCache = new Cache<UserId, { name: string }>();
userCache.set(uid, { name: "x" });
// userCache.set("plain", { name: "x" }); // error
// Function parameters that accept any id deliberately.
function logId(id: Brand<string, "UserId"> | Brand<string, "OrderId">): void {}A Map<UserId, V> and a Map<OrderId, V> are different types, so the wrong map cannot be passed to a function that expects the other. Where a function genuinely accepts several brands, the union is spelled out, and any other string is rejected — the type is doing the job a runtime registry would otherwise do.
Common mistakes and compiler errors
| Error or symptom | Cause | Fix |
|---|---|---|
TS2322: Type 'string' is not assignable to type 'UserId' | a plain value used where a brand is required | validate through the constructor |
TS2345: Argument of type 'OrderId' is not assignable to parameter of type 'UserId' | two brands mixed | pass the right id, or convert deliberately |
TS2352: Conversion of type 'X' to type 'UserId' may be a mistake | the base type is not assignable to the brand | cast through the base type, or use the constructor |
__brand appears in objects, JSON, or keyof | string-keyed brand | use a unique symbol key |
as UserId compiles on garbage | the cast skips validation | route creation through one validating function |
| Brand lost after a helper | the helper takes string | widen the helper's signature to the brand |
TS2339: Property '__brand' does not exist at runtime | reading the phantom field | never access it; it does not exist |
Branded value can't be used as a Record key | the brand is not a string | index with the base value after validation |
JSON.parse returns a branded value without error | any bypasses everything | parse into unknown and validate |
| Every function needs casts after introducing a brand | the brand is applied too widely | brand only at the trust boundary |
The judgment call is where a brand earns its noise. It pays for itself on values that are interchangeable in shape and dangerous to swap — ids of different entities, money in different currencies, measurements in different units, HTML that has been sanitized versus HTML that has not — and it is pure overhead on values that are already unique types. Apply it at the trust boundary, keep the constructor the only place a cast appears, and keep the signature of everything downstream branded; a brand that exists on the parameter but not in the repository's return type is a note the next function will not read.
Try matching browser tools
All toolsSmall utilities that fit TypeScript work — they run entirely in this browser tab, so nothing you paste leaves your device.
Related TypeScript guides
All TypeScript guidesTypeScript Generic Parameter Defaults: Syntax, Precedence, and Inference
When a default applies and when inference wins, defaults that reference earlier parameters, and how a defaulted type parameter keeps a library change non-breaking.
TypeScript Ambient Declarations: .d.ts Files, declare, and declare global
How declare and .d.ts files describe runtime values, wildcard modules for assets, declare global with var, and module augmentation of third-party types.
TypeScript Discriminated Unions: Exhaustiveness Checking and the never Type
Why the discriminant must be a literal, how never closes an exhaustive switch, and the duplicate-discriminant bug that lets a missing case compile.
TypeScript Enums: Numeric, String, const Enums, and Alternatives
How each enum form compiles, why numeric enums emit a reverse mapping, what const enums cost under per-file transpilation, and how an as const object replaces them.
More in TypeScript
All TypeScript guidesThe guides filed next to this one in TypeScript, in library order.