Created
January 3, 2019 04:53
-
-
Save zabirauf/6de9fd153a5ce7458c7b5756812cbeca to your computer and use it in GitHub Desktop.
Strongly typed currying in Typescript
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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