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

Practical Example: Generic map Over Container Types

Walking through a concrete implementation that maps functions over Array, Promise, or Option types uniformly.

Practical Example: Generic map Over Container Types

You'll learn how to implement a single generic map function that works uniformly across Array, Promise, and Option types using TypeScript's HKT simulation pattern.

The Power of Abstraction

Imagine you need to transform values inside different containers—arrays, promises, or maybe-types. Without generics, you'd write separate mapArray, mapPromise, mapOption functions. But with HKT-style simulation, you can write one map that understands the container it's working with.

Building a Unified map

Using the URI registry pattern you've learned, here's how to create a type-safe map that adapts to its container:

// Define container registrations
interface URItoKind<A> {
  Array: Array<A>;
  Promise: Promise<A>;
  Option: { tag: 'Some'; value: A } | { tag: 'None' };
}

// Extract available container names
type URIS = keyof URItoKind<unknown>;

// Generic map signature
type MapFn = <F extends URIS, A, B>(
  container: URItoKind<A>[F],
  fn: (value: A) => B,
  uri: F
) => URItoKind<B>[F];

// Implementation with runtime branching
const map: MapFn = (container: any, fn: any, uri: any): any => {
  if (uri === 'Array') {
    return (container as Array<any>).map(fn);
  }
  if (uri === 'Promise') {
    return (container as Promise<any>).then(fn);
  }
  if (uri === 'Option') {
    const opt = container as { tag: string; value?: any };
    return opt.tag === 'Some'
      ? { tag: 'Some', value: fn(opt.value) }
      : { tag: 'None' };
  }
};

// Type-safe usage
const nums: Array<number> = [1, 2, 3];
const doubled = map(nums, x => x * 2, 'Array'); // Array<number>

const asyncNum: Promise<number> = Promise.resolve(5);
const asyncDoubled = map(asyncNum, x => x * 2, 'Promise'); // Promise<number>

const someValue = { tag: 'Some' as const, value: 10 };
const optionDoubled = map(someValue, x => x * 2, 'Option'); // Option type

Why This Matters

The type system prevents you from passing an Array with URI 'Promise', giving you safety across container boundaries. The single map function adapts its behavior based on the URI tag while TypeScript tracks the correct input and output types.

Key Takeaway: HKT simulation lets you write container-agnostic functions like map that work uniformly across Arrays, Promises, and custom types while maintaining full type safety—though at the cost of runtime URI tags and implementation complexity.