【问题标题】:TypeScript call function with Rest Parameters from another with Rest Parameters带有 Rest 参数的 TypeScript 调用函数来自另一个带有 Rest 参数的函数
【发布时间】:2014-01-12 16:43:43
【问题描述】:

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

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

假设我声明了另一个名为 test1 的函数:

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

编译器产生这条消息:

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

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

【问题讨论】:

    标签: typescript


    【解决方案1】:

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

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

    【讨论】:

    • 这确实解决了这个问题。由于展开 ... 符号用于调用 test2,因此使用相同的符号 test1(...arguments) 调用 test1 会更加清晰
    【解决方案2】:

    没有办法将 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));
    }
    

    【讨论】:

      【解决方案3】:

      是的,它不会编译,因为你做错了。这里是the right way

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2017-02-17
        • 2014-12-31
        • 1970-01-01
        • 1970-01-01
        • 2019-06-28
        • 2018-10-12
        • 2012-09-27
        相关资源
        最近更新 更多