Currying and Function Composition Types
February 9, 20261 min readpart 18/20
Difficulty: Expert. Prerequisites: Tuple manipulation, recursive types, variadic tuples, function types.
Typing curried functions and function composition at the type level requires sophisticated manipulation of function signatures and parameter tuples. These patterns are essential for functional programming libraries like fp-ts and Ramda.
Key concepts
- Converting (a,b,c)⇒d to (a)⇒(b)⇒(c)⇒d
- Type-safe pipe and compose
- Partial application types
- Return type inference through function chains
Example
// Curry type
type Curry<F> = F extends (...args: infer A) => infer R
? A extends [infer F, ...infer Rest]
? Rest extends [] ? (a: F) => R : (a: F) => Curry<(...args: Rest) => R>
: R
: never;
type Orig = (a: string, b: number, c: boolean) => void;
type C = Curry<Orig>; // (a: string) => (a: number) => (a: boolean) => void
// Partial application (not the built-in Partial which makes props optional)
type PartialApply<F, A extends any[]> = F extends (...args: [...A, ...infer R]) => infer Ret
? (...args: R) => Ret : never;
type P1 = PartialApply<Orig, [string]>; // (b: number, c: boolean) => void
// Pipe type
declare function pipe<A, B>(f: (a: A) => B): (a: A) => B;
declare function pipe<A, B, C>(f: (a: A) => B, g: (b: B) => C): (a: A) => C;
declare function pipe<A, B, C, D>(f: (a: A) => B, g: (b: B) => C, h: (c: C) => D): (a: A) => D;
const process = pipe(
(x: string) => x.length,
(x: number) => x * 2,
(x: number) => x.toString()
); // (a: string) => string
// Real-world: fp-ts and Effect — overload-per-arity pattern (pipe has ~20 overloads)Resources
- Type Challenges - Currying: Currying challenge
- fp-ts Function Module: Production implementations
Practice
- Currying 1 (TypeHero, Hard)
- Currying 2 (TypeHero, Extreme)
- Currying 1 (Type Challenges, Hard)
- Currying 2 (with placeholders) (Type Challenges, Extreme)
- Drop String (Type Challenges, Hard)
- Query String Parser (Type Challenges, Extreme)
Hints
- To curry, recursively peel off the first parameter and wrap the rest in a new function type.
- For pipe/compose, chain the return type of one function to the parameter type of the next.