How to use “this” inside a class method with TypeScript?

Sometimes, we want to use “this” inside a class method with TypeScript.

In this article, we’ll look at how to use “this” inside a class method with TypeScript.

How to use “this” inside a class method with TypeScript?

To use “this” inside a class method with TypeScript, we can use it like we do in JavaScript.

For instance, we write

class Messenger {
  message = "Hello World";

  start() {
    setTimeout(() => alert(this.message), 3000);
  }
}

to use this inside the setTimeout callback, which is an arrow function that is inside the start method.

Therefore, this would still reference the Messenger instance since arrow functions don’t change the scope of this.

And using this in a method at the top level would reference the class instance.

Conclusion

To use “this” inside a class method with TypeScript, we can use it like we do in JavaScript.