打字稿:TS2496:ES3和ES5中的箭头函数不能引用'arguments'对象.考虑使用标准函数表达式

Dav*_*sco 9 socket.io angularjs typescript

我按照一些教程如http://www.html5rocks.com/en/tutorials/frameworks/angular-websockets/在我的node.js服务器和angular.js客户端实现socket.io,一切正常.

但是,客户端,Typescript显示以下编译错误:

TS2496: The 'arguments' object cannot be referenced in an arrow function in ES3 and ES5. Consider using a standard function expression.
Run Code Online (Sandbox Code Playgroud)

关于以下服务代码:

on(eventName:string, callback) {
  this.socket.on(eventName, () => {
    var args = arguments; // <-- here the compilation error
    this.$rootScope.$apply(() => {
      callback.apply(this.socket, args);
    });
  });
}

emit(eventName:string, data, callback?) {
  this.socket.emit(eventName, data, () => {
    var args = arguments; // <-- here the compilation error
    this.$rootScope.$apply(() => {
      if (callback) {
        callback.apply(this.socket, args);
      }
    });
  });
}
Run Code Online (Sandbox Code Playgroud)

我尝试了不同的解决方案,如https://github.com/Microsoft/TypeScript/issues/1609的第一篇文章中描述的解决方案,它修复了编译但打破了socket.io"on"功能(json对象不是'再解释一下).

知道如何修复或忽略这个打字稿编译错误吗?

Dav*_*ret 11

另一种可能性是使用rest参数而不是arguments:

on(eventName:string, callback) {
  this.socket.on(eventName, (...args) => {
    this.$rootScope.$apply(() => {
      callback.apply(this.socket, args);
    });
  });
}
Run Code Online (Sandbox Code Playgroud)


Ale*_* L. 6

使用function代替()=>

on(eventName:string, callback) {

        var self = this;
        this.socket.on(eventName, function() {
            var args = arguments;
            self.$rootScope.$apply(() => {
                callback.apply(self.socket, args);
            });
        });
    }
Run Code Online (Sandbox Code Playgroud)