Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generic curry function with n-arguments in typescript

I can create a generic currying function for functions with a set number of arguments. IE)

function curry2<T1,T2,R>(func:(arg1:T1, arg2:T2) => R, param2: T2):(arg:T1) => R{
    return (param1:T1) => func(param1, param2);
};

However, I cannot find a (typesafe) way to implement a generic curry function for a function with any number of arguments. In a different language I would name all my currying functions (ie: curry1, curry2, curry3, etc) the same thing (curry) and then have function overloading do the work of running the correct implementation of curry. However, typescript does not allow function overloading like this.

It isn't too bothersome to have to write curry2/curry1/curry3 everywhere instead of a single unified interface of curry, but if there is a way to do it I would appreciate knowing how!

like image 394
gnicholas Avatar asked Sep 11 '16 02:09

gnicholas


1 Answers

It isn't too bothersome to have to write curry2/curry1/curry3 everywhere instead of a single unified interface of curry,

You can with overloading (doc https://basarat.gitbooks.io/typescript/content/docs/types/functions.html)

More

Something to get you started:

function curry<T1,T2,R>(func:(arg1:T1, arg2:T2) => R, param2: T2):(arg:T1) => R;
function curry<T1,T2,T3,R>(func:(arg1:T1, arg2:T2, arg3: T3) => R, param2: T2):(arg:T1) => R;
function curry(){
    // Implement
    return undefined;
};
like image 177
basarat Avatar answered Nov 09 '22 10:11

basarat