We read every piece of feedback, and take your input very seriously.
To see all available qualifiers, see our documentation.
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
this
inference class methods contextually this parameter
Potentially related, but not the same (AFAICS): #1373
Inside of class methods, TypeScript knows what the type of this will be:
class Foo { value = 2 add(number: number) { return this.value + number; } } const foo = new Foo(); const result = foo.add(1);
However, when the class method is passed around, TypeScript does not prescribe the this type:
declare function pipeWith<A, B>(a: A, ab: (this: void, a: A) => B): B; // Runtime exception // Uncaught TypeError: Cannot read property 'value' of undefined // Expected type error but got none ❌ const result = pipeWith(1, foo.add);
For this to error as expected, it is necessary to explicitly define the type of this in the method signature:
- add(number: number) { + add(this: Foo, number: number) {
// Type error ✅ const result = pipeWith(1, foo.add);
Suggestion: TypeScript could contextually annotate the this type of class methods, so users don't need to remember to manually define it.
My suggestion meets these guidelines:
The text was updated successfully, but these errors were encountered:
Annnddd as soon as I filed this, I discovered an existing issue: #35451
Sorry, something went wrong.
No branches or pull requests
Search Terms
inference class methods contextually this parameter
Suggestion
Potentially related, but not the same (AFAICS): #1373
Inside of class methods, TypeScript knows what the type of
this
will be:However, when the class method is passed around, TypeScript does not prescribe the
this
type:For this to error as expected, it is necessary to explicitly define the type of
this
in the method signature:Suggestion: TypeScript could contextually annotate the
this
type of class methods, so users don't need to remember to manually define it.Use Cases
Examples
Checklist
My suggestion meets these guidelines:
The text was updated successfully, but these errors were encountered: