首页 文章

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

提问于
浏览
15

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

function test1(p1: string, ...p2: string[]) {
    // Do something
}

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

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

编译器生成此消息:

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

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

3 回答

  • 18

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

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

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

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

    那是在使用Function.prototype.applyarguments对象 .

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

    function test2(p1: string, ...p2: string[]) {
        test1.apply(this, [p1].concat(p2));
    }
    
  • 1

    是的,它没有编译,因为你做错了 . 这是the right way

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

相关问题