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

Encoding Functors with HKT Simulation

Implementing map-like operations that work across different container types using the HKT pattern.

Encoding Functors with HKT Simulation

What you'll learn: How to implement generic map-like operations that work across different container types (like Array, Promise, Option) using TypeScript's HKT simulation pattern.

Now that you understand the mechanics of HKT simulation, let's build something practical: a functor interface that works uniformly across different container types.

The Core Problem

You want to write a map function that works on arrays, promises, or custom types like Option<T>, but TypeScript can't express "any type constructor that holds a value" without simulating higher-kinded types.

The Functor Pattern

A functor is any container type that supports a map operation—transforming the wrapped value without changing the container's structure.

Using HKT simulation, you first encode each container type:

// The HKT registry
interface URItoKind<A> {
  Array: Array<A>;
  Promise: Promise<A>;
  Option: Option<A>;
}

type URIS = keyof URItoKind<unknown>;

type Kind<F extends URIS, A> = URItoKind<A>[F];

Next, define the Functor interface that works with any encoded container:

interface Functor<F extends URIS> {
  map: <A, B>(fa: Kind<F, A>, f: (a: A) => B) => Kind<F, B>;
}

This says: "For any container type F, provide a map that transforms Kind<F, A> into Kind<F, B>."

Now implement functors for specific types:

const ArrayFunctor: Functor<'Array'> = {
  map: (arr, f) => arr.map(f)
};

const PromiseFunctor: Functor<'Promise'> = {
  map: (promise, f) => promise.then(f)
};

Why This Matters

You've created a uniform abstraction for mapping operations. Functions can now accept Functor<F> and work with any container type, enabling highly generic, reusable functional programming patterns.

Key Takeaway: HKT simulation lets you encode functors in TypeScript—interfaces for map-like operations that work uniformly across Arrays, Promises, and custom container types, enabling powerful generic abstractions despite the language's limitations.