~/alexsh.blog

$ cat advanced-typescript/19-higher-kinded-type-simulation.md

Higher-Kinded Type (HKT) Simulation

February 9, 20261 min readpart 19/20

Difficulty: Expert. Prerequisites: Advanced generics, declaration merging, functional programming concepts.

Higher-kinded types are type constructors (like Array without a type argument). TypeScript doesn't natively support HKTs, but simulation patterns enable Functor, Monad, and other FP abstractions through URI-based encoding and declaration merging.

Key concepts

  • Type constructors vs concrete types
  • URI-based HKT simulation (fp-ts approach)
  • Defunctionalization via interface merging
  • Implementing Functor, Monad generically

Example

codets
// URI to Kind mapping
interface URItoKind<A> {
  Array: Array<A>;
  Option: Option<A>;
}

type URIS = keyof URItoKind<any>;
type Kind<URI extends URIS, A> = URItoKind<A>[URI];

// Option type
type Option<A> = { _tag: 'Some'; value: A } | { _tag: 'None' };
const some = <A>(a: A): Option<A> => ({ _tag: 'Some', value: a });
const none: Option<never> = { _tag: 'None' };

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

// Implementations
const arrayF: Functor<'Array'> = { map: (fa, f) => fa.map(f) };
const optionF: Functor<'Option'> = {
  map: (fa, f) => fa._tag === 'None' ? none : some(f(fa.value))
};

// Generic over any Functor
function double<F extends URIS>(F: Functor<F>, fa: Kind<F, number>): Kind<F, number> {
  return F.map(fa, n => n * 2);
}

double(arrayF, [1, 2, 3]);  // [2, 4, 6]
double(optionF, some(5));   // Some(10)

// Real-world: fp-ts — each data type registers via declare module './HKT' augmentation

Resources

Practice

Hints

  • Use an interface as a registry that maps URI strings to concrete types.
  • Declaration merging lets you add new type constructors to the registry from anywhere.