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

Declaring Brand Symbols

Using declare and unique symbol to create compile-time-only brand markers that add no runtime overhead.

Declaring Brand Symbols

What you'll learn: How to create compile-time-only brand markers using declare and unique symbol that add zero runtime overhead while preventing type substitution.

The Problem with Basic Brands

You've learned how to create branded types using intersection types like string & { readonly brand: 'UserId' }. But that brand property, while never accessed at runtime, still suggests a runtime structure. TypeScript offers a more elegant solution: declared unique symbols that exist only at compile time.

What Are Declared Unique Symbols?

A declared unique symbol is a type created with two keywords working together:

  • declare tells TypeScript "this exists for type-checking only, emit nothing"
  • unique symbol creates a symbol type that's guaranteed to be distinct from all others

Think of it like a watermark visible only under UV light—invisible in normal use, but detectable when you need verification.

The Syntax

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

Each unique symbol in a type position creates a distinct, incomparable type. Even though both brands use __brand with unique symbol, TypeScript treats them as completely different types.

Why This Is Better

Zero runtime footprint: The declare keyword isn't needed here because unique symbol in a type position is already compile-time only. No property actually exists.

Unforgeable: Unlike string literal brands, you cannot accidentally create matching structures. unique symbol is truly unique.

Cleaner semantics: The type system understands these are abstract markers, not real properties.

Creating Branded Values

function createUserId(id: string): UserId {
  return id as UserId;
}

function createOrderId(id: string): OrderId {
  return id as OrderId;
}

The casting is required because we're adding phantom type information. This is the controlled entry point to your branded type.

Key Takeaway: Using unique symbol in brand declarations creates truly unique, zero-overhead compile-time markers that prevent accidental type substitution with no runtime cost.