Skip to content

Phantom Type

In one line

Phantom types are unused type parameters that add compile-time distinctions without runtime cost.

In simple words

A phantom type is a generic type parameter that never appears in the actual data — it exists only at the type level to create distinctions.

For example, type Meter<T> = number — T doesn't appear in the value (it's always a number), but different T values create different types: Meter<"distance"> vs Meter<"time">.

This lets you tag values with metadata at the type level:

  • State machines (Idle vs Running states)
  • Units (meters vs seconds)
  • Capabilities (authorized vs unauthorized)
  • Phases of computation

No runtime cost — the phantom parameter is erased. It's purely a compile-time safety mechanism.

Example

typescript
// Phantom type — T is never used in the value
type Tagged<T extends string> = { readonly _tag: T; value: number };

type Meters = Tagged<"distance">;
type Seconds = Tagged<"time">;

function speed(d: Meters, t: Seconds): number {
  return d.value / t.value;
}

const dist: Meters = { _tag: "distance", value: 100 };
const time: Seconds = { _tag: "time", value: 10 };

console.log(speed(dist, time)); // 10
// speed(time, dist); // Error! Wrong types

Meters and Seconds are both { value: number } at runtime, but the _tag phantom distinguishes them at compile time. Can't swap them in speed().

Common confusions

  • Confused with: branded type

    The difference: A branded type adds a phantom property to the value (intersects with { __brand: 'X' }). A phantom type uses a type parameter that doesn't appear in the value at all. Both create compile-time distinctions; branded types use properties, phantom types use unused type parameters.

Related terms

Related Resources

Related Lessons

Decode error messages

Plain-English explanations of common errors — what they mean, why they happen, and how to fix them.

View errors

← Back to glossary