带有Rest参数的RestScript参数的TypeScript调用函数

Col*_*ame 19 typescript

在TypeScript中,可以使用"Rest Parameters"声明一个函数:

function test1(p1: string, ...p2: string[]) {
    // Do something
}
Run Code Online (Sandbox Code Playgroud)

假设我声明了另一个调用的函数test1:

function test2(p1: string, ...p2: string[]) {
    test1(p1, p2);  // Does not compile
}
Run Code Online (Sandbox Code Playgroud)

编译器生成此消息:

提供的参数与调用目标的任何签名都不匹配:无法将类型'string'应用于类型为'string []'的参数2.

如何test2调用test1提供的参数?

Sco*_*nro 22

试试Spread Operator.它应该允许与Jeffery的答案相同的效果,但具有更简洁的语法.

function test2(p1: string, ...p2: string[]) {
    test1(...arguments);
}
Run Code Online (Sandbox Code Playgroud)


Jef*_*ski 12

没有办法将p1和p2从test2传递给test1.但你可以这样做:

function test2(p1: string, ...p2: string[]): void {
    test1.apply(this, arguments);
}
Run Code Online (Sandbox Code Playgroud)

这是使用Function.prototype.applyarguments对象.

如果您不喜欢arguments对象,或者您不希望所有参数以完全相同的顺序传递,您可以执行以下操作:

function test2(p1: string, ...p2: string[]) {
    test1.apply(this, [p1].concat(p2));
}
Run Code Online (Sandbox Code Playgroud)