~/alexsh.blog

$ cat advanced-typescript/13-branded-types.md

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

codets
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 input

Resources

Practice

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.