microsoft / TypeScript

TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
https://www.typescriptlang.org
Apache License 2.0
100.27k stars 12.39k forks source link

Check when a function that uses `this` is referenced without binding it #59994

Open u130b8 opened 2 days ago

u130b8 commented 2 days ago

🔍 Search Terms

this binding

✅ Viability Checklist

⭐ Suggestion

I've recently started using TypeScript and was porting ES5 function classes to ES6 classes and I've noticed an unchecked case related to passing references to class methods and this binding that could be statically analyzed.

Consider this example:

class MyServer {
    server: net.Server;
    counter: number;

    constructor() {
        this.server = net.createServer(this.onConnection);
        this.counter = 0;
    }

    onConnection(socket: net.Socket) {
        this.counter++;
    }
}

This will always fail because we're passing a reference to a class function that references this in the class. The onConnection callback will always throw a TypeError unless it's called with the proper this binding:

this.server = net.createServer(() => this.onConnection()); // OK
this.server = net.createServer(this.onConnection.bind(this)); // OK

In the example above, net.createServer(this.onConnection) is a bug that could be caught at compile time: a function is referencing this, passing it by reference (or binding it to a variable) does not preserve its this context, so any calls through it would produce an error (unless the function is never called, or the caller will call it with a correct this).

At compile time, any references to a function using this in its scope can result in errors or warnings unless it is bound or is called from the same this scope context (can be silenced with !)

📃 Motivating Example

This feature helps prevent bugs that will result in runtime type errors at compile time.

💻 Use Cases

  1. What do you want to use this for? To catch and prevent type errors

  2. What shortcomings exist with current approaches? This is currently not checked

  3. What workarounds are you using in the meantime? Checking it manually

MartinJohns commented 2 days ago

Duplicate of #7968.