Course contentsShow
← TypeScript
Lesson 1350 of 1,79631. Type-Driven DesignFree lesson

Brand Technique with Intersection

Creating branded types using intersection with a unique symbol property to prevent accidental substitution.

What You'll Learn

You'll learn how to create branded types using intersection types and unique symbol properties to prevent TypeScript from accidentally treating two structurally identical types as interchangeable.


The Substitution Problem (Recap)

Structural typing means TypeScript doesn't care about type names — only shape. If UserId and OrderId are both just number, TypeScript happily lets you pass a UserId where an OrderId is expected. This is dangerous.


The Brand Technique with Intersection

The brand technique solves this by adding a fake, unique property to each type using a symbol and an intersection type.

Here's the pattern:

type UserId = number & { readonly __brand: unique symbol };
type OrderId = number & { readonly __brand: unique symbol };

Each type is now an intersection of number and an object with a unique symbol property. The unique symbol ensures each brand is incompatible with every other.


Why This Works

  • The __brand property uses unique symbol, which TypeScript treats as a distinct type every time it appears
  • The intersection (&) combines number with this branded object
  • TypeScript sees UserId and OrderId as structurally different — they can't be substituted
  • The property is readonly to prevent runtime manipulation
  • At runtime, the brand property doesn't exist — this is a compile-time-only phantom type

Using Branded Types

type UserId = number & { readonly __brand: unique symbol };
type OrderId = number & { readonly __brand: unique symbol };

function getUser(id: UserId) {
  // implementation
}

const userId = 42 as UserId; // You must cast to create branded values
const orderId = 99 as OrderId;

getUser(userId);   // ✓ works
getUser(orderId);  // ✗ Type error: OrderId not assignable to UserId

You typically use helper functions to construct branded types safely, avoiding raw casts everywhere.


Key Takeaway: The brand technique uses intersection types with unique symbol properties to create nominal-like types in TypeScript's structural system, preventing accidental type substitution while maintaining zero runtime overhead.