[英]typescript error TS2339 when using method from another class in event handler and binding current class context
I have a service which handles all of my dom manipulation called DomService
我有一个处理我所有dom操作的服务,称为DomService
I have another service handling modal functionality called ModalService
我还有另一个服务处理模式功能,称为ModalService
In ModalService
I'm binding a few events and giving it a method from DomService
as the listener which looks like: 在ModalService
我绑定了一些事件,并从DomService
提供了一个方法作为侦听器,如下所示:
document.body.addEventListener('focus', this.domService.keyPress.bind(this), true);
and then keyPress looks something like: 然后keyPress看起来像:
keyPress(event){
if (event.which === key.escape) {
event.preventDefault();
this.hide();
}
}
It works fine, the problem is typescript stills sees this
as a reference to the DomService
class when it's actually bound to the ModalService
class, so it's telling me the hide
property doesn't exist on type DomService
它工作正常,问题是打字稿剧照认为this
是对一个参考DomService
时,它实际上是绑定到类ModalService
类,所以它告诉我的hide
属性的类型不存在DomService
Is there anything I can do to get typescript to chill? 有什么我可以做的让打字稿变冷的方法?
You can change the context of this
in any function by adding it (and its type) as the first argument to the function. 你可以改变的背景下this
把它加(及其类型)作为第一个参数传递给函数的任何功能。 So to change the context of this
inside keyPress
to be a ModalService
, you would do: 因此,要改变的背景下this
里面keyPress
是一个ModalService
,你会怎么做:
keyPress(this: ModalService, event) {
if (event.which === key.escape) {
event.preventDefault();
this.hide(); // Now is OK.
}
}
You can read more about that feature here . 您可以在此处阅读有关该功能的更多信息。
In addition to that, you can always add a line // @ts-ignore
above any line creating an error to silence it, if the above solution isn't sufficient. 除此之外,如果上述解决方案还不够,您总是可以在任何行上方添加// @ts-ignore
,从而创建一个错误以使其静音。
You can use EventEmitter and handle (subscribe) "emit" event. 您可以使用EventEmitter并处理(订阅)“发出”事件。
ModalService 模态服务
this.subscriptionHide = this.domService.getHideEmitter()
.subscribe(() => this.hide());
DomService DomService
hideEmitter: EventEmitter<any> = new EventEmitter();
keyPress(event){
if (event.which === key.escape) {
event.preventDefault();
this.hideEmitter.emit(null);
}
}
getHideEmitter() {
return this.hideEmitter;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.