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

The Generic Problem HKTs Solve

How HKTs enable writing code generic over containers like map over Array, Promise, or Option without duplication.

The Generic Problem HKTs Solve

You'll learn: How Higher-Kinded Types (HKTs) would let you write code generic over containers like map over Array, Promise, or Option without duplication.

The Container Problem

Imagine you want to write a map function. Easy enough for arrays:

function mapArray<A, B>(arr: A[], fn: (a: A) => B): B[] {
  return arr.map(fn);
}

But what if you want the exact same logic for Promise?

function mapPromise<A, B>(promise: Promise<A>, fn: (a: A) => B): Promise<B> {
  return promise.then(fn);
}

Or for an Option type (representing a value that may or may not exist)?

type Option<T> = { kind: 'Some'; value: T } | { kind: 'None' };

function mapOption<A, B>(option: Option<A>, fn: (a: A) => B): Option<B> {
  if (option.kind === 'None') return option;
  return { kind: 'Some', value: fn(option.value) };
}

Notice the pattern? You're duplicating the concept of "apply a function inside a container." The logic differs, but the shape is identical: take a container of A, a function from A to B, and produce a container of B.

What HKTs Would Enable

With true Higher-Kinded Types, you could write one generic map function that works for any container type:

// Pseudo-code — TypeScript doesn't support this!
function map<Container, A, B>(
  container: Container<A>,
  fn: (a: A) => B
): Container<B>

The key insight: Container itself would be a type parameter—not Array<T> or Promise<T>, but the idea of "array-ness" or "promise-ness" abstracted away.

This lets you write transformation logic once and reuse it across Array, Promise, Option, Result, or any custom container you create—without code duplication and with full type safety.

Why TypeScript Lacks This

TypeScript's type system doesn't allow types to take other types as parameters in this abstract way. You can't write Container<A> where Container is a variable representing "some generic wrapper type."

Key Takeaway: HKTs solve the problem of writing generic operations (like map, flatMap, filter) once for all container types, eliminating duplication while preserving type safety—but TypeScript doesn't support them natively, forcing developers to repeat similar logic for each container.