Typescript Icon Get 42% off the TypeScript bundle

See the bundle then add to cart and your discount is applied.

0 days
00 hours
00 mins
00 secs

Write TypeScript like a pro. Typescript Icon

Follow the ultimate TypeScript roadmap.

Typing "this" Keyword in TypeScript

Using the this keyword in JavaScript often trips developers up, whether they’re a beginner or more experienced.

If you’re new to TypeScript, you’ll likely encounter a scenario where you need to type the this keyword to bulletproof a section of code.

With things like the class keyword, we don’t need to worry too much. TypeScript will infer the type. But what if we don’t know the type?

We need to be explicit in places where TypeScript is unaware of its surroundings.

Let’s take this simple example:

const element = document.querySelector('button');

function handleClick() {
  // ⚠ No errors, uh-oh!

element.addEventListener('click', handleClick);

A fairly innocent looking example, and by default we may see no compiler errors depending on your tsconfig.json.

Let’s ensure we have "noImplicitThis" added:

// tsconfig.json
  "compilerOptions": {
    "target": "esnext",
    "noImplicitThis": true

At this point, you will definitely see an error:

function handleClick() {
  // ❌ 'this' implicitly has type 'any' because it does not have a type annotation.

Great! TypeScript is telling us of a weakspot in our code, let’s fix it up.

To add the this type definition to our function, first we must be using a function declaration syntax, and secondly the way we type this is through the function arguments (however it is not to be confused as a parameter):

function handleClick(this: HTMLButtonElement) {
  // ✅ this = HTMLButtonElement

And that’s it! You can of course specify more function parameters, for things like the event:

function handleClick(this: HTMLButtonElement, event: Event) {
  console.log(this.innerText); // Click me!
  console.log(event.target.innerText); // Click me!

Here’s the full code in a StackBlitz if you’d like a play around:

And there you have it, a fully typed this keyword in TypeScript. That’s just scratching the surface, there’s so much more to uncover, but this is a great start.

🚀 There’s so much more to TypeScript that I can teach you. Fast track your skills overnight with my deep-dive TypeScript Courses and take your skills to the top.

Thanks for reading!

Learn TypeScript the right way.

The most complete guide to learning TypeScript ever built.
Trusted by 82,951 students.

Todd Motto

with Todd Motto

Google Developer Expert icon Google Developer Expert

Related blogs 🚀

Free eBooks:

Angular Directives In-Depth eBook Cover

JavaScript Array Methods eBook Cover

NestJS Build a RESTful CRUD API eBook Cover