CrazySynthax
CrazySynthax

Reputation: 15064

Typescript: why doesn't it treat 'this' as Javascript?

I wrote the following code:

export class ClickHandlers {
    static entityNameClickHandler(id) {
       console.log("EntityNameClickHandler");        
       // add the new subTree to the end of historySubTree
       this.history.addToHistory(id);
       this.refreshEntityContentElem(this);
    }
}

in another file:

addEventListenersToEntityInExplorer(elem, id) {
      elem.find('[data-id ^= "expand_"]').click(ClickHandlers.expandButtonHandler);
      elem.find('[data-id ^= "entity"]').click(function() {
         ClickHandlers.entityNameClickHandler.call(this, id)
      }.bind(this));

}

I get an error for the lines: this.history.addToHistory(id); this.refreshEntityContentElem(this);

The error is:

Error:(25, 12) TS2339:Property 'history' does not exist on type 'typeof ClickHandlers'.

What I understand is that Typescript looks at 'this' as the class ClickHanlders. However, I called function 'ClickHandlers.entityNameClickHandler' using 'call', so 'this' is not necessarily the wrapping object.

Upvotes: 1

Views: 66

Answers (2)

Nitzan Tomer
Nitzan Tomer

Reputation: 164457

Since you are changing this inside the function then you need to tell that to the compiler.
You can do that since typescript version 2.0 by Specifying the type of this for functions:

type MyType = {
    history: any;
    refreshEntityContentElem: (obj: any) => void;
}

export class ClickHandlers {
    static entityNameClickHandler(this: MyType, id) {
       console.log("EntityNameClickHandler");        
       // add the new subTree to the end of historySubTree
       this.history.addToHistory(id);
       this.refreshEntityContentElem(this);
    }
}

Upvotes: 2

Serginho
Serginho

Reputation: 7490

You have to forget javascript if you want to work with Typescript. Typescript throws errors even the code works properly. It's javascript with lots of things that now you can't do, but you will get a clearer code and with less errors.

Error:(25, 12) TS2339:Property 'history' does not exist on type 'typeof ClickHandlers'.

This error says that if you want to use this.[property], this property should be defined as a class variable or in any of parent classes.

As I can see here: this.refreshEntityContentElem(this);, I can figure out you should read a Object Programming Oriented tutorial.

Upvotes: 0

Related Questions