Compiler option for implicitly adding this context on class member methods #28548
Labels
Add a Flag
Any problem can be solved by flags, except for the problem of having too many flags
In Discussion
Not yet reached consensus
Suggestion
An idea for TypeScript
Search Terms
this context class
Suggestion
A new compiler option
--enforceClassMemberThisContext
. It causes the compiler to implicitly set thethis
context of class methods which use this somewhere in the method body and behave as the user had done this manually on each method.Use Cases
It is pretty common to pass class methods down to other parts of the program as event listeners (e.g. in react apps). In this case it is almost always necessary to bind the
this
context to the current class instance if the method usesthis
in some form. A common mistake is to miss this binding for a given method. It is possible to add a typescript check for this mistake (by specifying thethis
-"parameter" on each class method) but one would have to do this for each method by hand, which is also easy to miss. By specifying it as a compiler flag, it would become very hard to make this mistake.Examples
The following example doesn't raise a typescript error in current typescript but would do so with the proposed compiler flag:
This example produces a "The 'this' types of each signature are incompatible." error in current typescript and is identical to the example above with the proposed compiler flag:
Problems/Discussion Points
element.addEventListener
at the moment because theEventListener
interface doesn't specify or complain about wrong this contexts (but I think it should, maybe this is another separate issue?)Checklist
My suggestion meets these guidelines:
The text was updated successfully, but these errors were encountered: