Typescript 函数类型定义中的类型脚本扩展
我想创建一个Typescript函数,它接受任何其他函数和参数列表,并使用给定参数调用给定函数。例如:Typescript 函数类型定义中的类型脚本扩展,typescript,typing,Typescript,Typing,我想创建一个Typescript函数,它接受任何其他函数和参数列表,并使用给定参数调用给定函数。例如: function thisDoesSomething(arg1: string, arg2: int) { // do something } callMyFunction(thisDoesSomething, "a string", 7); 对于函数的定义,我尝试了以下方法: function callMyFunction<T>(toCall: (...T) =>
function thisDoesSomething(arg1: string, arg2: int) {
// do something
}
callMyFunction(thisDoesSomething, "a string", 7);
对于函数的定义,我尝试了以下方法:
function callMyFunction<T>(toCall: (...T) => any, ...args: T) {
toCall(...args);
}
function callMyFunction(toCall:(…T)=>any,…args:T){
toCall(…args);
}
然而,这当然不起作用。有什么方法可以实现我在typescript中的目标吗?您已经非常接近了,您可以在typescript 3.0中使用
function callMyFunction(toCall:(…a:T)=>any,…args:T){
toCall(…args);
}
函数ThisDoesMething(arg1:string,arg2:number){
//做点什么
}
callMyFunction(thisdoeSomething,“一个字符串”,7);
callMyFunction(thisdoesmething,“一个字符串”,“7”);//错误
您的代码只有两个问题,第一个问题是T
必须扩展数组类型,第二个问题是toCall
的参数必须有一个名称,您声明它的方式是toCall
有一个名为T
的参数,其类型为any
function callMyFunction<T extends any[]>(toCall: (...T) => any, ...args: T) {
return toCall(...args);
}
您还可以使用函数原型方法call
和apply
,如下所示:
//call:
thisDoesSomething.call(this, "a string", 7);
//apply:
thisDoesSomething.apply(this, ["a string", 7]);
function callMyFunction(toCall: Function, ...args: any[]) {
return toCall(...args);
}
//call:
thisDoesSomething.call(this, "a string", 7);
//apply:
thisDoesSomething.apply(this, ["a string", 7]);