Pages

Topics

Tools

↑↓navigate↵openescclose
All guides

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.

~6 min readTypeScript
#TypeScript#Nominal Typing#Type Safety
3D illustration of structural primitive strings receiving holographic brand stamps that prevent cross-assignment

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 UserId on 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 symbol key is a stronger brand than a string key: it cannot collide with a real property and does not show up in keyof as an ordinary name.
  • Brands survive object types (Pick, property access) but disappear through JSON.parse, spread into a wider type, and any index signature that accepts plain strings.
  • Units are the other natural use: Meters, Seconds, and Cents as 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

typescript
// 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:

typescript
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

TechniquePrevents mixing same-shape valuesRuntime costSurvives JSONTooling clarity
Branded intersectionyesnonenoerror names the brand
unique symbol brandyes, and cannot collidenonenostrongest of the type-only options
Wrapper class / recordyesallocationwith serializersneeds mapping code
Enum of allowed valuesonly closed setsobject emityesenum overhead
Runtime validation library (zod, io-ts)yesparse costyesschema doubles as validator
Nothing (plain string)nononeyeszero

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

typescript
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 record

The 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

typescript
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 results

Branded 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

typescript
// 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.

typescript
// Reading a stored value: validate, then brand. function loadUserId(row: { user_id: string }): UserId { return toUserId(row.user_id); }

4. Where brands leak

typescript
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 UserId

Two 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

typescript
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 symptomCauseFix
TS2322: Type 'string' is not assignable to type 'UserId'a plain value used where a brand is requiredvalidate through the constructor
TS2345: Argument of type 'OrderId' is not assignable to parameter of type 'UserId'two brands mixedpass the right id, or convert deliberately
TS2352: Conversion of type 'X' to type 'UserId' may be a mistakethe base type is not assignable to the brandcast through the base type, or use the constructor
__brand appears in objects, JSON, or keyofstring-keyed branduse a unique symbol key
as UserId compiles on garbagethe cast skips validationroute creation through one validating function
Brand lost after a helperthe helper takes stringwiden the helper's signature to the brand
TS2339: Property '__brand' does not exist at runtimereading the phantom fieldnever access it; it does not exist
Branded value can't be used as a Record keythe brand is not a stringindex with the base value after validation
JSON.parse returns a branded value without errorany bypasses everythingparse into unknown and validate
Every function needs casts after introducing a brandthe brand is applied too widelybrand 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 tools

Small utilities that fit TypeScript work — they run entirely in this browser tab, so nothing you paste leaves your device.

All TypeScript guides

More in TypeScript

All TypeScript guides

The guides filed next to this one in TypeScript, in library order.