使用Rest参数从另一个使用Rest参数的函数调用TypeScript函数

使用Rest参数从另一个使用Rest参数的函数调用TypeScript函数,typescript,Typescript,在TypeScript中,可以使用“Rest参数”声明函数: 假设我声明了另一个调用test1的函数: function test2(p1: string, ...p2: string[]) { test1(p1, p2); // Does not compile } 编译器生成以下消息: 提供的参数与调用目标的任何签名不匹配: 无法将类型“string”应用于类型为“string[]”的参数2 test2如何调用test1调用提供的参数?无法将p1和p2从test2传递到test1

在TypeScript中,可以使用“Rest参数”声明函数:

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

function test2(p1: string, ...p2: string[]) {
    test1(p1, p2);  // Does not compile
}
编译器生成以下消息:

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


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

无法将p1和p2从test2传递到test1。但你可以这样做:

function test2(p1: string, ...p2: string[]): void {
    test1.apply(this, arguments);
}
这是在利用和对象

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

function test2(p1: string, ...p2: string[]) {
    test1.apply(this, [p1].concat(p2));
}
试试这个。它应该允许与中相同的效果,但具有更简洁的语法

function test2(p1: string, ...p2: string[]) {
    test1(...arguments);
}

是的,它不会编译,因为您正在做错误的事情。这是:


全面的回答!这确实解决了这个问题。随着时间的推移。。。符号用于调用test2,使用相同的符号test1(…参数)调用test1更清晰
function test2(p1: string, ...p2: string[]) {
    test1(...arguments);
}
function test1(p1: string, ...p2: string[]) {
    // Do something
}

function test2(p1: string, ...p2: string[]) {
    test1(p1, ...p2);
}