Created
December 13, 2021 19:06
-
-
Save Willmo36/62533b7f977a443540170955a4adb017 to your computer and use it in GitHub Desktop.
TypeScript variadic currying
This file contains 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 ArgsToFunc<Args extends [...any]> = Args extends [infer LastArg, infer Result] | |
? (a: LastArg) => Result //last argument case | |
: Args extends [infer Arg, ...infer Args, infer Result] // n-1 argument case | |
? (a: Arg) => ArgsToFunc<[...Args, Result]> | |
: never //Args was not a 2tuple, abort | |
function curry<F extends (...args: any) => any>(fn: F): ArgsToFunc<[...Parameters<F>, ReturnType<F>]> { | |
return null as any; //todo - I'm just playing at the type level | |
} | |
function add(a: number, b: number): number { | |
return a + b; | |
} | |
const addC = curry(add); | |
function myFunction(a: number, b: string, c: boolean): "foobar" { | |
return "foobar" | |
} | |
const myFunctionC = curry(myFunction); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment