When passing a function reference as a parameter to another function and then calling it elsewhere, the context of "this" gets lost. To avoid this issue, I have to convert the method into an arrow function. Here's an example to illustrate:
class Meeseeks{
private line="I'm mister Meeseeks";
lookAtMe(){ console.log(this.line+', look at me!'); }
}
// somewhere else:
let mr = new Meeseeks();
mr.lookAtMe();/// works fine
function callIt(fn:Function){ fn(); }
callIt(mr.lookAtMe);/// throws "Uncaught TypeError: Cannot read property 'line' of undefined"
The only solution is to change "lookAtMe" to an arrow function:
lookAtMe = () => console.log(this.line+', look at me!');
My question is: Is there a way for TypeScript to alert me when I use a function reference in this manner? I prefer catching errors during compilation rather than at runtime, which is why I use TypeScript (as I appreciate statically typed languages). However, having to make all methods arrow functions to prevent this issue can be detrimental to inheritance.
Do you know of any tsconfig or tslint configurations that can help with this?