The This Type

What

In JavaScript, the value of this depends on how a function is called, which can lead to bugs. TypeScript can explicitly type the this context to prevent these issues.

How

You can add a special this parameter as the first argument of a method to define its expected context. This parameter is removed during compilation:

class Counter {
  count = 0;
  
  increment(this: Counter) {
    this.count++;
  }
}

const c = new Counter();
c.increment(); // OK

Why

Explicit this parameters are useful when a method is passed as a callback (e.g., to an event listener) and you want to ensure the compiler flags cases where the context might be lost. It provides a layer of safety for one of JavaScript’s most confusing features.

Summary

While usually inferred correctly, explicit this parameters provide extra safety for complex method contexts.