打字稿在函数类型定义中传播

时间:2018-10-03 09:38:28

标签: typescript typing

我想创建一个Typescript函数,该函数接受任何其他函数和参数列表,并使用给定参数调用给定函数。例如:

function thisDoesSomething(arg1: string, arg2: int) {
    // do something
}
callMyFunction(thisDoesSomething, "a string", 7);

对于函数的定义,我尝试了以下方法:

function callMyFunction<T>(toCall: (...T) => any, ...args: T) {
    toCall(...args);
}

但是,这当然不起作用。有没有办法实现我在打字稿中的目标?

2 个答案:

答案 0 :(得分:3)

您非常接近,您可以在Typescript 3.0中使用Tuples in rest parameters and spread expressions进行此操作。

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

答案 1 :(得分:0)

function callMyFunction<T extends any[]>(toCall: (...T) => any, ...args: T) {
    return toCall(...args);
}

或更简单,没有泛型类型

function callMyFunction(toCall: Function, ...args: any[]) {
    return toCall(...args);
}

还可以使用函数原型方法callapply,如下所示:

//call:
thisDoesSomething.call(this, "a string", 7);
//apply:
thisDoesSomething.apply(this, ["a string", 7]);
相关问题