Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

create a generic function returning a function with the same signature

In Typescript I want to create a function that will take a function and return a function with the same input-output. the function itself needs to be generic. so that it can take any number of arguments and return any type.

function improveFunction <T,U>(func:'that takes T and returns U') : (T):U {
  var newFunc = doDomethingToTheFunction(func); 
  return newFunc;
}

if I was returning the function itself this would work. But since I am using the arguments special parameter to be able to accept any number of argument I am in fact creating a new function that the typescript compiler can't understand.

Edit:

I made one more variant to go from

(U => T) to (U => Promise<T>)

function ddd<T>(func: (...x: any[]) => T) : (...x: any[]) => ng.IPromise<T> {
    // return a function returning a promise of T;
}
like image 549
user1852503 Avatar asked Mar 11 '15 22:03

user1852503


1 Answers

Here you go :

function f<A extends Function>(a:A):A {
    var newFunc = (...x:any[]) => {
        console.log('('+x.join(',')+') => ', a.apply(undefined, x));
        return null;
    }
    return <any>newFunc;
}

function a(j:string, k:number): boolean {
    return j === String(k);
}

var b = f(a);

b("1", 1);
b("a", 2);
b('123','123'); // ERROR
like image 115
basarat Avatar answered Oct 22 '22 23:10

basarat