简体   繁体   English

Angular2将编译器错误引发给在subscribe()中运行的内容

[英]Angular2 throws compiler error to something run in a subscribe()

I have a textarea on which I want to listen to keyup events. 我有一个文本区域,我想在上面监听按键事件。 Everything works fine except that Angular2 throws an error compile-time (not runtime). 除了Angular2抛出错误编译时(而不是运行时)之外,其他所有东西都工作正常。

The error: 错误:

error TS2339: Property 'target' does not exist on type '{}'. 错误TS2339:类型“ {}”上不存在属性“目标”。

The code: 编码:

Observable.fromEvent(this.editor.nativeElement, 'keyup')
          .debounceTime(500)
          .subscribe(event => this.hasError = !this.isValidJSON(event.target.value));

Obviously the error is suggesting that event is an empty object. 显然,该错误表明该event是一个空对象。

As I said, the keyup event and my application runs fine but this error is annoying and I want to get rid of it. 就像我说的那样,keyup事件和我的应用程序运行良好,但是此错误很烦人,我想摆脱它。 How can it complain about event being an empty object during compile-time ? 在编译时如何抱怨事件为空对象? It has never even been run, and during run-time everything works. 它甚至从未运行过,并且在运行时一切正常。

You need to cast to the appropriate type: 您需要强制转换为适当的类型:

I suggest you cast to KeyboardEvent (which inherits from ES6's Event ) or, if you just want to get rid of the error use any : 我建议您转换为KeyboardEvent (继承自ES6的Event ),或者,如果您只是想摆脱错误,请使用any

subscribe((event: KeyboardEvent) => ...);

or 要么

subscribe((event: any) => ...);

If you just use Event there might be a mixup with Event automatically imported from @angular/router . 如果仅使用Event则可能会发生从@angular/router自动导入Event

[ [ 1]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM