Course contentsShow
← TypeScript
Lesson 1428 of 1,79632. Advanced PatternsFree lesson

The Phantom Type Builder Pattern

Use phantom type parameters to encode builder state without runtime overhead, ensuring compile-time safety.

The Phantom Type Builder Pattern

What you'll learn: How to use phantom type parameters—types that exist only at compile time and carry no runtime data—to encode builder state and enforce compile-time safety without any runtime overhead.

The Core Idea

A phantom type is a type parameter that doesn't actually appear in the runtime data structure. It exists purely to track information in the type system. In the builder pattern, phantom types can encode which methods have been called so far, preventing you from building an incomplete object or calling methods in the wrong order.

Think of it like a stamp card at a coffee shop: the card tracks which stamps you've collected, but the stamps themselves aren't physical things you carry around—they're just markers of state. Similarly, phantom types mark the state of your builder without adding any runtime fields.

How It Works

You create a builder class with a type parameter that represents its current state. Each method returns a new type with an updated state parameter. TypeScript's type system tracks this progression, but the actual JavaScript object remains unchanged.

The key insight: the type parameter doesn't correspond to any property. It's a "phantom" that exists only for the compiler.

Encoding State Without Runtime Cost

By using branded types or unique symbols as state markers, you can create distinct types that are identical at runtime. The builder progresses through states like Incomplete, HasName, Complete, and TypeScript enforces that you can only call .build() when you've reached the Complete state.

This gives you the safety of a state machine with zero runtime overhead—no boolean flags, no property checks, just pure compile-time enforcement.

Key Takeaway: Phantom type parameters let you encode stateful progression in builders at the type level, preventing incomplete construction without adding any runtime checks or data fields.