8

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;
}

1 Answer 1

11

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
4
  • Just in time! i just found a similar solution to this myself:) by doing a double casting <T><any>function(){}. but this is better. thanks man. i mean it's still a double cast, one is just implicit. but using the ...x syntax is sweet. Mar 11, 2015 at 22:35
  • Genius! Where do you find this stuff?
    – frodo2975
    Aug 11, 2015 at 19:00
  • 1
    Lots of spare time coding ... sadly no shortcut as far as I know :( Wasn't born super smart ... just smart enough
    – basarat
    Aug 13, 2015 at 0:01
  • There is one problem with this code though... The f function is typed as if it would return the same value as its a argument, but it's returning null. The code above would be consistent with the typing: ts function f<A extends Function>(a:A):A { let newFunc = (...x:any[]) => { let result = a.apply(undefined, x) console.log('('+x.join(',')+') => ', ); return result; } return <any>newFunc; } I'm using let but var would be good enough as well. Apr 7, 2021 at 18:56

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.