use*_*503 6 generics typescript
在Typescript中,我想创建一个函数,它将获取一个函数并返回一个具有相同输入输出的函数.函数本身需要是通用的.这样它可以接受任意数量的参数并返回任何类型.
function improveFunction <T,U>(func:'that takes T and returns U') : (T):U {
var newFunc = doDomethingToTheFunction(func);
return newFunc;
}
Run Code Online (Sandbox Code Playgroud)
如果我返回功能本身,这将工作.但由于我使用arguments特殊参数来接受任意数量的参数,实际上我正在创建一个typescript编译器无法理解的新函数.
编辑:
我又做了一个变种
(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;
}
Run Code Online (Sandbox Code Playgroud)
干得好 :
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
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1574 次 |
| 最近记录: |