Categories
TypeScript Answers

How to declare the type of ‘this’ in a TypeScript function?

Spread the love

Sometimes, we want to declare the type of ‘this’ in a TypeScript function.

In this article, we’ll look at how to declare the type of ‘this’ in a TypeScript function.

How to declare the type of ‘this’ in a TypeScript function?

To declare the type of ‘this’ in a TypeScript function, we can add the fake this parameter in our functions.

For instance, we write

class Handler {
  info: string;

  onClick(this: Handler, e: Event) {
    this.info = e.message;
  }
}

const h = new Handler();

to add the this parameter into onClick and set it to type Handler.

The parameter will be discarded after it’s compiled.

But it’ll let the TypeScript compiler check for valid properties for this.

Conclusion

To declare the type of ‘this’ in a TypeScript function, we can add the fake this parameter in our functions.

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 *