Course contentsShow
← TypeScript
Lesson 1490 of 1,79634. The Limits of TypeScriptFree lesson

The Lightweight Higher-Kinded Types Trick

Exploring the fp-ts approach using declaration merging and phantom types to encode kind information.

The Lightweight Higher-Kinded Types Trick

You'll learn: How to encode kind information using declaration merging and phantom types to simulate higher-kinded types in TypeScript.

The Core Idea

Since TypeScript doesn't natively support higher-kinded types, the "lightweight" trick uses a clever combination of features you already know: declaration merging and phantom types (type parameters that never appear in runtime values). This approach, popularized by the fp-ts library, creates a fake "registry" where type constructors can look up their element types.

Think of it like a phone book: instead of calling a function directly with a type parameter it doesn't know about yet, you create a central registry interface where types can register themselves and be looked up later.

The Pattern

You declare a global interface that acts as a registry:

interface URItoKind<A> {
  // Initially empty - types register themselves here
}

Each type constructor declares a unique string literal type (its URI) and merges into this interface:

type ArrayURI = "Array"

// Declaration merging: add Array's entry
interface URItoKind<A> {
  Array: Array<A>
}

Now you can write generic code that works with "any container" by referring to the URI:

type Kind<F, A> = F extends keyof URItoKind<A> 
  ? URItoKind<A>[F] 
  : never

// Kind<"Array", number> resolves to Array<number>

This lets you write functions polymorphic over container types without TypeScript having native HKT support.

Why It Works

The phantom type <A> in URItoKind<A> never exists at runtime—it's purely for the type system to track which element type to use. Declaration merging allows each container to add itself to the registry independently. The Kind helper does the lookup.

Key Takeaway: TypeScript simulates higher-kinded types by using declaration merging to create a type-level registry, with phantom types threading element information through string literal URIs.