typescript / expert
Snippet
Higher-Order Variadic Function Currying Type Inference
This snippet implements complete type-level function currying using variadic tuple inference. By recursing over function argument tuples with 'infer Head' and 'infer Tail', TypeScript enforces correct type checking and auto-completion at each invocation step of the curried chain.
snippet.ts
typescript
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
type Curried<Args extends any[], Return> = Args extends [infer Head, ...infer Tail]? Tail extends []? (arg: Head) => Return: (arg: Head) => Curried<Tail, Return>: () => Return;function curry<Args extends any[], Return>(fn: (...args: Args) => Return): Curried<Args, Return> {return function curried(...args: any[]): any {if (args.length >= fn.length) {return fn(...(args as any));}return (nextArg: any) => curried(...args, nextArg);} as Curried<Args, Return>;}const addThree = (a: number, b: string, c: boolean): string => `${a}-${b}-${c}`;const curriedAdd = curry(addThree);const result = curriedAdd(42)("hello")(true);
Breakdown
1
type Curried<Args extends any[], Return> = Args extends [infer Head, ...infer Tail]
Destructures function argument tuples into the first argument type (Head) and remaining argument tuple (Tail).
2
? (arg: Head) => Curried<Tail, Return>
Returns a unary function expecting Head that evaluates to another Curried type for the Tail parameters.
3
function curry<Args extends any[], Return>(fn: (...args: Args) => Return): Curried<Args, Return>
Wraps a standard multi-parameter function into its type-safe curried representation.
4
const result = curriedAdd(42)("hello")(true);
Executes sequentially chained unary calls, preserving accurate parameter types at each step.