Typescript 在函数类型定义中的传播
Typescript spread in function type definition
我想创建一个 Typescript 函数,它接受任何其他函数和一个参数列表,并使用给定的参数调用给定的函数。例如:
function thisDoesSomething(arg1: string, arg2: int) {
// do something
}
callMyFunction(thisDoesSomething, "a string", 7);
对于函数的定义,我尝试了以下方法:
function callMyFunction<T>(toCall: (...T) => any, ...args: T) {
toCall(...args);
}
不过,这当然不行。有什么方法可以在打字稿中实现我的目标吗?
你非常接近,你可以使用 Tuples in rest parameters and spread expressions 在 Typescript 3.0 中做到这一点。
function callMyFunction<T extends unknown[]>(toCall: (...a: T) => any, ...args: T) {
toCall(...args);
}
function thisDoesSomething(arg1: string, arg2: number) {
// do something
}
callMyFunction(thisDoesSomething, "a string", 7);
callMyFunction(thisDoesSomething, "a string", "7"); // error
您的代码只有两个问题,首先 T
必须扩展数组类型,其次 toCall
的参数必须有一个名称,您声明它的方式 toCall
有一个名为 T
的隐含类型 any
的参数。
function callMyFunction<T extends any[]>(toCall: (...T) => any, ...args: T) {
return toCall(...args);
}
或者没有泛型类型甚至更简单
function callMyFunction(toCall: Function, ...args: any[]) {
return toCall(...args);
}
还有函数原型方法call
和apply
可以使用,像这样:
//call:
thisDoesSomething.call(this, "a string", 7);
//apply:
thisDoesSomething.apply(this, ["a string", 7]);
我想创建一个 Typescript 函数,它接受任何其他函数和一个参数列表,并使用给定的参数调用给定的函数。例如:
function thisDoesSomething(arg1: string, arg2: int) {
// do something
}
callMyFunction(thisDoesSomething, "a string", 7);
对于函数的定义,我尝试了以下方法:
function callMyFunction<T>(toCall: (...T) => any, ...args: T) {
toCall(...args);
}
不过,这当然不行。有什么方法可以在打字稿中实现我的目标吗?
你非常接近,你可以使用 Tuples in rest parameters and spread expressions 在 Typescript 3.0 中做到这一点。
function callMyFunction<T extends unknown[]>(toCall: (...a: T) => any, ...args: T) {
toCall(...args);
}
function thisDoesSomething(arg1: string, arg2: number) {
// do something
}
callMyFunction(thisDoesSomething, "a string", 7);
callMyFunction(thisDoesSomething, "a string", "7"); // error
您的代码只有两个问题,首先 T
必须扩展数组类型,其次 toCall
的参数必须有一个名称,您声明它的方式 toCall
有一个名为 T
的隐含类型 any
的参数。
function callMyFunction<T extends any[]>(toCall: (...T) => any, ...args: T) {
return toCall(...args);
}
或者没有泛型类型甚至更简单
function callMyFunction(toCall: Function, ...args: any[]) {
return toCall(...args);
}
还有函数原型方法call
和apply
可以使用,像这样:
//call:
thisDoesSomething.call(this, "a string", 7);
//apply:
thisDoesSomething.apply(this, ["a string", 7]);