0Pricing
TypeScript Academy · Lesson

Generic Functors and Mappers

Write map functions generic over any container.

A Generic Functor

Now we use the encoding for its purpose: a generic map that works over any registered container. The Functor interface, parameterized by a URI, declares one method.

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

The Array Instance

An instance implements map for one URI. The Array instance maps with the built-in array method. Its Kind<"Array", A> resolves to A[].

const arrayFunctor: Functor<"Array"> = {
  URI: "Array",
  map: (fa, f) => fa.map(f)
};

All lessons in this course

  1. The HKT Problem in TypeScript
  2. Defining Type Constructors
  3. The Lightweight HKT Pattern
  4. Generic Functors and Mappers
← Back to TypeScript Academy