Created
September 10, 2025 19:55
-
-
Save gutchom/58eff8b0a1a7552fbb13393ded55af00 to your computer and use it in GitHub Desktop.
A type safe curry function
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 Curry = <A extends unknown[], R>( | |
| fn: (...arg: readonly [...A]) => R, | |
| ) => Curried<A, R>; | |
| type Curried<A extends unknown[], R> = <T extends unknown[]>( | |
| ...arg: readonly [...T] | |
| ) => T extends A ? R : A extends [...T, ...infer U] ? Curried<U, R> : never; | |
| const curry: Curry = | |
| <A extends unknown[], R>(fn: (...arg: readonly [...A]) => R): Curried<A, R> => | |
| <T extends unknown[]>( | |
| ...args: readonly [...T] | |
| ): T extends A ? R : A extends [...T, ...infer U] ? Curried<U, R> : never => | |
| fn.length <= args.length | |
| ? fn.apply(this, args) | |
| : curry(fn).bind(this, ...args); | |
| function add(x: number, y: number, z: number): number { | |
| return x + y + z; | |
| } | |
| var a = curry(add); | |
| var b = a(1, 2); | |
| var c = b(3); | |
| console.log(c); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment