Categories
TypeScript Answers

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

Spread the love

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.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *