Description
π Search Terms
losing this context of method
undefined this
π Version & Regression Information
all versions
β― Playground Link
π» Code
class A {
a = 10;
f() { console.log(this.a); } // Error: Cannot read properties of undefined (reading 'a')
}
let obj = new A();
let f = obj.f;
f();
π Actual behavior
No compiler error. Runtime error occurs.
π Expected behavior
There should be a compile error when casting a class method that uses "this" to a simple arrow function type.
Additional information about the issue
I suppose this problem with losing "this" context has been discussed here before, although I couldn't find it.
It's clear that in the general case, when dealing with abstract interfaces, this situation is difficult to detect. But in this case, the implementation of the class method is directly called. So why can't Typescript see that "this" is used there and throw an error when trying to cast to an arrow function? Yes, this will only be a partial solution, but it's definitely better than no solution.
But in general, it would be necessary to clearly separate the signatures of methods and arrow functions and prohibit casting the former to the latter, because now, as I see, TS makes no difference between them.
So the type of the "f" method should be something special, like "A.()=>void" or something else, meaning binding to class A and not allowing a separate call.
I suggest adding a separate option for this in the compiler settings.