Simulating Opaque Types with Branding
You'll learn: How to create truly distinct types from primitives by adding a phantom property that exists only at compile time.
In the previous lesson, you saw that branding can prevent accidentally mixing up types. Now let's understand the elegant trick that makes it work: phantom properties.
The Core Idea
An opaque type appears to have a unique property in TypeScript's type system, but that property doesn't exist at runtime. It's a "phantom"—visible to the compiler, invisible to JavaScript.
The syntax looks like this:
type UserId = string & { readonly __brand: "UserId" };
This creates a type that is:
- Structurally a string (at runtime, it is just a string)
- Nominally distinct (TypeScript treats it as incompatible with plain strings)
Why the Phantom Property Works
The __brand property creates a unique shape. TypeScript's structural type system says: "This type has a property called __brand with the literal value "UserId". No other type has that exact shape, so this type is unique."
But here's the magic: you never actually add this property to your values. It exists only in the type layer. At runtime, your UserId is still just a string.
type UserId = string & { readonly __brand: "UserId" };
type OrderId = string & { readonly __brand: "OrderId" };
declare const userId: UserId;
declare const orderId: OrderId;
// TypeScript prevents mixing them
const wrongAssignment: UserId = orderId; // ❌ Error
The readonly modifier prevents accidental assignment of the brand, and using a unique string literal ("UserId" vs "OrderId") ensures each branded type is distinct.
Key Takeaway: Opaque types use phantom properties—fields that exist only in TypeScript's type system—to create nominally distinct types from primitives without any runtime overhead.