Branded Types (Nominal Typing)
February 9, 20261 min readpart 13/20
Difficulty: Intermediate. Prerequisites: Type assertions, type guards, intersection types.
Branded types create nominally distinct types that are structurally identical but not assignable to each other. This prevents bugs like passing a UserId where a PostId is expected, and enables compile-time validation guarantees.
Key concepts
- Creating brand symbols using unique symbol
- Distinguishing structurally identical types (UserId vs PostId)
- Validation functions returning branded types
- Integration with validation libraries like zod
Example
declare const brand: unique symbol;
type Brand<T, B> = T & { [brand]: B };
// Distinct ID types
type UserId = Brand<string, 'UserId'>;
type PostId = Brand<string, 'PostId'>;
function getUser(id: UserId) {}
function getPost(id: PostId) {}
const uid = 'u1' as UserId;
const pid = 'p1' as PostId;
getUser(uid); // OK
getUser(pid); // Error!
// Validated types
type Email = Brand<string, 'Email'>;
function validateEmail(s: string): Email | null {
return s.includes('@') ? s as Email : null;
}
function sendEmail(to: Email, subject: string) {}
const email = validateEmail('a@b.com');
if (email) sendEmail(email, 'Hello'); // Type-safe!
// Real-world: Effect-TS brands with phantom symbol (zero-cost at runtime)
type Branded<A, K extends string | symbol> = A & { readonly [Symbol.for('Brand')]: { readonly [k in K]: K } };
type EUserId = Branded<string, 'UserId'>;
// const UserId = Brand.nominal<UserId>() — constructor just returns inputResources
- Type-Level TypeScript - Branded Types: Nominal typing patterns
- Zod: Validation with brands built-in
Practice
- Opaque Types (Branded) (TypeHero, Medium)
- Nominal Typing (TypeHero, Medium)
- Type Lookup (Type Challenges, Medium)
- Branded Types Workshop (Total TypeScript, Medium)
- Zod Brand Practice (Zod Docs, Medium)
Hints
- Use a unique symbol as a brand key to make types nominally distinct.
- Create validation functions that return branded types to enforce runtime checks at the boundary.