Skip to content

Problem of losing "this" context in class method when casting to arrow function #61684

Closed as not planned
@Perfectoff

Description

@Perfectoff

πŸ”Ž Search Terms

losing this context of method
undefined this

πŸ•— Version & Regression Information

all versions

⏯ Playground Link

https://www.typescriptlang.org/play/?ts=5.8.3#code/MYGwhgzhAECC0G8BQ1XTNAvNAjABgG4U0AzACgEpFpgB7AOwlpAFMA6EWgczIBcALAJYQ2YCgWgBfVAHoZ0AMJh69Wr2gAnFmAAm0AA4ba+lht6CWMWiWgBXejpYlB9FnrJbdLrtADkYXwokSSRWdVoAIwArLGhXAHc4SiJQlnUbAC5oSkwAPgA3WkE9bEiothIU8nEgA

πŸ’» 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.

Metadata

Metadata

Assignees

No one assigned

    Labels

    DuplicateAn existing issue was already created

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions