问题描述
我有一个服务,它处理我所有的dom操作,称为 DomService
I have a service which handles all of my dom manipulation called DomService
我还有另一个服务处理模式功能,称为 ModalService
I have another service handling modal functionality called ModalService
在 ModalService
中,我绑定了一些事件,并为它提供了一个来自 DomService
的方法,作为监听器,如下所示:
In ModalService
I'm binding a few events and giving it a method from DomService
as the listener which looks like:
document.body.addEventListener('focus',this.domService.keyPress.bind(this),true);
然后keyPress类似于:
and then keyPress looks something like:
keyPress(event){
if (event.which === key.escape) {
event.preventDefault();
this.hide();
}
}
它工作正常,问题是打字稿在实际绑定到 ModalService
类时仍然看到 this
作为对 DomService
类的引用,所以它告诉我 DomService
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
有什么办法可以使打字稿变冷?
Is there anything I can do to get typescript to chill?
推荐答案
您可以在任何函数中更改 this
的上下文,方法是将其(及其类型)添加为函数的第一个参数.因此,要将 keyPress
中的 this
的上下文更改为 ModalService
,您可以执行以下操作:
You can change the context of this
in any function by adding it (and its type) as the first argument to the function. So to change the context of this
inside keyPress
to be a ModalService
, you would do:
keyPress(this: ModalService, event) {
if (event.which === key.escape) {
event.preventDefault();
this.hide(); // Now is OK.
}
}
您可以在此处了解更多有关该功能的信息.
You can read more about that feature here.
除此之外,如果上述解决方案还不够,您总是可以在任何行上方添加行//@ ts-ignore
,从而创建错误以使其静音.
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.
这篇关于在事件处理程序中使用另一个类的方法并绑定当前类上下文时,打字稿错误TS2339的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!