Explicit this: this
annotation necessary to catch unbound class method errors with --no-implicit-this
#35451
Labels
Design Limitation
Constraints of the existing architecture prevent this from being fixed
TypeScript Version: 3.7.2
Search Terms:
this
binding,--no-implicit-this
, methods,this: this
Expected behavior: The unbound
this
error is raised in both cases.Actual behavior: The compiler only catches the error in the case where the method was annotated as
this: this
.Related Issues: Found many
this
issues, couldn't find any related to the default inferred value in the absence of athis
annotation on class methods. Sorry if I've just missed it.Code
Output
Compiler Options
Playground Link: Provided
Given this behavior, I've submitted a PR to typescript-eslint adding a linter rule that requires these annotations on all (non-arrow function) class methods that use
this
.However, I was wondering if there was a way this could be resolved on the Typescript compiler's side. The two code examples above seem semantically identical to me, and it's strange that they type-check differently. Is there a reason why it'd be harmful for
this: this
to be inferred from class methods that lack an explicit type annotation?Naturally, it would have to be behind a flag, but this is one of the few areas where I've hit runtime errors that the TS compiler hasn't caught. It's led to our codebase being somewhat paranoid about attaching methods to the prototype, preferring to define almost all methods as arrow function instance properties, which is a bit unfortunate from a memory perspective.
Or perhaps there's some downside to
this: this
that makes it unsuitable as a general practice, and I shouldn't have a lint rule enforcing that at all! Any insight on the current behavior would be appreciated.Thanks!
The text was updated successfully, but these errors were encountered: