Skip to content
New issue

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

Suggestion: contextually type this in class methods #36100

Closed
4 of 5 tasks
OliverJAsh opened this issue Jan 9, 2020 · 1 comment
Closed
4 of 5 tasks

Suggestion: contextually type this in class methods #36100

OliverJAsh opened this issue Jan 9, 2020 · 1 comment

Comments

@OliverJAsh
Copy link
Contributor

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:

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.

Use Cases

Examples

Checklist

My suggestion meets these guidelines:

  • This wouldn't be a breaking change in existing TypeScript/JavaScript code
  • This wouldn't change the runtime behavior of existing JavaScript code
  • This could be implemented without emitting different JS based on the types of the expressions
  • This isn't a runtime feature (e.g. library functionality, non-ECMAScript syntax with JavaScript output, etc.)
  • This feature would agree with the rest of TypeScript's Design Goals.
@OliverJAsh
Copy link
Contributor Author

Annnddd as soon as I filed this, I discovered an existing issue: #35451

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant