【问题标题】:How to implement ES6 Spread Syntax on angular 6如何在 Angular 6 上实现 ES6 扩展语法
【发布时间】:2019-10-02 12:35:18
【问题描述】:

我正在使用带有 Angular 6 版本的 Angular CLI。我面临实施传播语法的问题。

这里是代码示例,

...
baseFunction(): void {
const params = [a, b, c];
const output = this.spreadFunction(...params);
console.log(output);
}

spreadFunction(attribute1, attribute2, attribute3 ): string {

...
return 'anything';

}

错误消息:预期有 3 个参数,但得到了 0 个或更多。

注意: 没有什么有用的更新 "target": "es5", 到 tsconfig.json 上的 "target": "es6"

提前致谢。

【问题讨论】:

    标签: angular ecmascript-6 syntax spread


    【解决方案1】:

    大声笑,这里也检查一下:

    TypeScript type not working with spread operator

    另外,我确实找到了一种不使用扩展运算符的方法,有一种方法可以使用 Object.assign

    正如在上面的链接中找到的,我找到了另一种方法,只需使用 JSON.stringify,然后再次使用 JSON.parse,这将创建一个新实例。

    【讨论】:

      【解决方案2】:

      那么你实际上不需要在spreadFunction中获取三个参数,你可以在那里只使用一个参数:-

      spreadFunction(...params): string {
        // code here
        // it will output the array passed at the time of calling the function
        console.log(params)
        // return 'anything';
      }
      

      use of spread operator

      请参阅下面的 sn-p(尽管它并非完全是 typescript)。

      function baseFunction() {
        const params = ['a', 'b', 'c'];
        const output = spreadFunction(...params);
      }
      
      function spreadFunction(...params) {
        // code here
        // console.log(params);
        const [attribute1, attribute2, attribute3] = params;
        console.log(attribute1);
        console.log(attribute2);
        console.log(attribute3);
      }
      
      // do action here
      baseFunction();

      【讨论】:

      • 您好 Rohit,感谢您的回答。但是,如果我将按照您的示例使用 ...params 的 spreadFunction 参数,那么这将无法完全满足编码要求,因为为此我将需要再次使用 params 作为数组,因为 es6 spread 运算符会自动执行此操作并且将它们转换为函数参数。
      • @ArpanDas 你可以破坏参数,我更新了答案。扩展运算符在运行时将它们转换为函数参数,因此打字稿编译器会抱怨它。
      • 是的,更新后的想法更有帮助。谢谢!虽然我想使用扩展运算符语法而不编写任何额外的代码。
      猜你喜欢
      • 2020-02-24
      • 1970-01-01
      • 2017-12-24
      • 1970-01-01
      • 2018-05-01
      • 2018-06-29
      • 1970-01-01
      相关资源
      最近更新 更多