Common Use Cases: curry and compose
What you'll learn: How variadic tuples enable type-safe implementations of functional programming utilities like curry and compose.
Why This Matters
Functional programming patterns like currying and function composition are powerful, but historically they've been a nightmare to type correctly in TypeScript. Variadic tuples finally give us the tools to preserve complete type information through these transformations.
Currying with Variadic Tuples
Currying transforms a multi-parameter function into a chain of single-parameter functions. With variadic tuples, you can type this accurately:
type Curry<P extends unknown[], R> =
P extends [infer First, ...infer Rest]
? (arg: First) => Rest extends [] ? R : Curry<Rest, R>
: R;
function curry<P extends unknown[], R>(
fn: (...args: P) => R
): Curry<P, R> {
return ((...args: unknown[]) => {
if (args.length >= fn.length) {
return fn(...args as P);
}
return curry((fn as any).bind(null, ...args));
}) as Curry<P, R>;
}
// Fully type-safe!
const add = (a: number, b: number, c: number) => a + b + c;
const curriedAdd = curry(add);
const result = curriedAdd(1)(2)(3); // number
Function Composition
Compose chains functions right-to-left, and variadic tuples preserve types through the entire chain:
type Compose<Fns extends unknown[]> =
Fns extends [(...args: infer A) => infer B, ...infer Rest]
? Rest extends [(arg: B) => infer C, ...infer Tail]
? Compose<[(arg: infer A) => C, ...Tail]>
: (...args: A) => B
: never;
// Usage preserves end-to-end types
const double = (n: number) => n * 2;
const toString = (n: number) => String(n);
const shout = (s: string) => s.toUpperCase();
// Type flows through: number → string → string
Key Takeaway: Variadic tuples transform curry and compose from type-unsafe hacks into fully type-safe utilities that preserve parameter types, return types, and intermediate transformations throughout the call chain.