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;
}
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With