typescript 29 lines · 8 steps

Type-safe currying in TypeScript

A recursive conditional type gives a runtime curry helper full argument-by-argument type safety.

Explained by highlit
1type Curried<A extends any[], R> = A extends [infer First, ...infer Rest]
2 ? (arg: First) => Rest extends [] ? R : Curried<Rest, R>
3 : R;
4 
5function curry<A extends any[], R>(
6 fn: (...args: A) => R
7): Curried<A, R> {
8 function collect(collected: any[]): any {
9 if (collected.length >= fn.length) {
10 return fn(...(collected as A));
11 }
12 return (arg: any) => collect([...collected, arg]);
13 }
14 return collect([]) as Curried<A, R>;
15}
16 
17const request = (method: string, baseUrl: string, path: string): string =>
18 `${method} ${baseUrl}${path}`;
19 
20const curriedRequest = curry(request);
21 
22const get = curriedRequest("GET");
23const getFromApi = get("https://api.example.com");
24 
25const users = getFromApi("/users");
26const orders = getFromApi("/orders");
27 
28const post = curriedRequest("POST")("https://api.example.com");
29const createUser = post("/users");
01 / 01
STEP 01

Walkthrough

Space play step click any line
Three takeaways
  1. 1A recursive conditional type can model a function's shape one argument at a time, so each partial application stays typed.
  2. 2Currying is just closures accumulating arguments until enough are collected to call the original function.
  3. 3Runtime logic can stay loosely typed with `any` while a carefully written type signature restores full safety at the boundary.

Related explainers

Share this explainer

Here's the card — post it anywhere.

Type-safe currying in TypeScript — share card
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code