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

Type-Level Apply Functions

Building Apply or $<F, A> helpers that resolve the final concrete type from a constructor representation.

Type-Level Apply Functions

What you'll learn: How to build an Apply or $<F, A> helper that resolves the final concrete type from a constructor representation.


Understanding Type-Level Apply

When simulating higher-kinded types in TypeScript, you have type constructors (like Array, Promise) represented as interfaces with a type property. But how do you actually apply an argument to get the concrete type back?

A type-level apply function is the bridge. It takes your constructor representation and a type argument, then returns the final, usable type.

Think of it like a vending machine: You insert a code (the constructor) and a coin (the type argument), and out comes your actual snack (the concrete type).


Building the Basic Apply Helper

The simplest pattern uses a generic type that extracts the type property from your constructor interface:

// Your constructor representation
interface ArrayKind<A> {
  type: Array<A>;
}

// The Apply helper
type Apply<F, A> = F extends { type: infer T } 
  ? (T extends any ? T : never) 
  : never;

// Usage
type NumberArray = Apply<ArrayKind<number>, number>; // number[]

Wait—that's not quite right. We need to substitute A properly.


The Correct Apply Pattern

The trick is using conditional types to extract and substitute:

type $<F, A> = (F & { argument: A }) extends { type: infer T } 
  ? T 
  : never;

// Now with a constructor that uses 'argument'
interface ArrayKind {
  type: Array<this['argument']>;
  argument: unknown;
}

type NumberArray = $<ArrayKind, number>; // number[]
type StringArray = $<ArrayKind, string>; // string[]

The $<F, A> helper intersects your constructor F with { argument: A }, making the substitution available inside the type property via this['argument'].


Why This Matters

This pattern lets you write generic algorithms over type constructors:

type Map<F, Tuple extends any[]> = Tuple extends [infer Head, ...infer Tail]
  ? [$<F, Head>, ...Map<F, Tail>]
  : [];

type Result = Map<ArrayKind, [number, string]>; // [number[], string[]]

You've abstracted the "container" from the transformation logic.


Key Takeaway: Type-level apply functions like $<F, A> resolve concrete types from constructor representations by substituting type arguments through intersection and conditional type extraction—the essential mechanism for simulating higher-kinded type application in TypeScript.