Skip to content

Instantly share code, notes, and snippets.

@zabirauf
Created January 3, 2019 04:53
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save zabirauf/6de9fd153a5ce7458c7b5756812cbeca to your computer and use it in GitHub Desktop.
Save zabirauf/6de9fd153a5ce7458c7b5756812cbeca to your computer and use it in GitHub Desktop.
Strongly typed currying in Typescript
type Func = (...args: any[]) => any;
type FirstParam<T extends Func> =
T extends (arg: infer J, ...args: infer U) => infer V
? J
: never;
type TailParams<T extends Func> =
T extends (arg: infer J, ...args: infer U) => infer V
? U
: never;
type CurriedFunc<T extends Func> = (...args: TailParams<T>) => ReturnType<T>;
function curry<T extends Func>(val: FirstParam<T>, func: T): CurriedFunc<T> {
return (...args: TailParams<T>) => {
return func(val, ...args);
}
}
function add(x: number, y: number): number {
return x + y;
}
const add7 = curry(7, add);
const val = add7(4);
console.log(val);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment