Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.0k views
in Technique[技术] by (71.8m points)

typescript - 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;
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share
...