When sending methods to other classes, a common issue is the context of this
getting mixed up. Take a look at this straightforward example:
class Counter {
public count: number
private callMyCallback: CallMyCallback
constructor() {
this.count = 0
// works
this.callMyCallback = new CallMyCallback(() => this.countFunctionCalls())
// doesn't work (Cannot read properties of undefined (reading 'count'))
this.callMyCallback = new CallMyCallback(this.countFunctionCalls)
}
private countFunctionCalls() {
console.log("Callback called")
this.count = this.count + 1;
}
}
class CallMyCallback {
constructor(callback: ()=> void) {
callback();
}
}
const counter = new Counter()
console.log(counter.count)
The issue here is that both methods of passing the callback function to callMyCallback
are compiled without any error or warning. Using this
incorrectly can only be identified when actually running the application. I haven't come across any relevant tsconfig setting or useful solution yet. Is there any configuration/library available to enforce the proper usage of this
?