Kolby
Kolby

Reputation: 2865

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

I have another service handling modal functionality called ModalService

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);

and then keyPress looks something like:

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

Is there anything I can do to get typescript to chill?

Upvotes: 0

Views: 453

Answers (3)

Thiago Martins
Thiago Martins

Reputation: 119

You can use EventEmitter and handle (subscribe) "emit" event.

ModalService

this.subscriptionHide = this.domService.getHideEmitter()
  .subscribe(() => this.hide());

DomService

hideEmitter: EventEmitter<any> = new EventEmitter();

keyPress(event){
    if (event.which === key.escape) {
        event.preventDefault();
        this.hideEmitter.emit(null);
    }
}

getHideEmitter() {
    return this.hideEmitter;
}

Upvotes: 1

CRice
CRice

Reputation: 32166

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.

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.

Upvotes: 2

Thiago Martins
Thiago Martins

Reputation: 119

Try change your functions to arrow functions.

Change

keyPress(event) {

To

keyPress = (event) => {

You can read about arrow functions in typescript here

Upvotes: 0

Related Questions