【问题标题】:Using Typescript spread operator results in compile error使用 Typescript 展开运算符会导致编译错误
【发布时间】:2017-04-30 01:10:33
【问题描述】:

在 TS 2.1 中使用 VS17RC

function foo(x:number, y:number, z:number) { console.log(x + y + z)}
var args = [0, 1, 2];
foo(...args);

给出编译时错误“提供的参数与调用目标的任何签名都不匹配。”

这是编译好的js:

function foo(x, y, z) { console.log(x + y + z); }
var args = [0, 1, 2];
foo.apply(void 0, args);

这确实有效。

我在这里做错了吗?

例子来自这里:Typescript Deep Dive

【问题讨论】:

    标签: typescript typescript2.1


    【解决方案1】:

    这是我的解决方法:

    /**
     * Function definition
     */
    class SockService {
      connect(...args:Array<string>) {
        if (args.length > 1) {
          [this.host, this.path] = args;
        }
      }
    }
    
    /**
     * Function usage
     */
    var endpoint = {
      'local_test': [] as Array<string>,
      'local': ['0.0.0.0:8080', '/foo/websocket'],
      'production': ['192.0.2.1:8080', '/foo/websocket']
    };
    
    this.sock.connect(...endpoint.local_test);
    

    我不喜欢这样使用剩余参数,因为它使函数定义的描述性大大降低。但这是我在 TypeScript 中使用函数参数的唯一方法。

    【讨论】:

      【解决方案2】:

      在完全相同的示例上有一个未解决的问题:
      Compiler incorrectly reports parameter/call target signature mismatch when using the spread operator

      这个问题被标记为bug,但它是从 2015 年 8 月 3 日开始出现的,并且没有固定的里程碑。

      【讨论】:

      • 好吧,现在解释一下。
      猜你喜欢
      • 2014-02-08
      • 2019-04-06
      • 1970-01-01
      • 2016-05-01
      • 2015-10-03
      • 1970-01-01
      • 2020-01-26
      • 1970-01-01
      • 2017-04-08
      相关资源
      最近更新 更多