Get super confident at TypeScript. Typescript Icon

I promise to change your TypeScript skills!

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!
  console.log(this.innerText);
}

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.
  console.log(this.innerText);
}

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
  console.log(this.innerText);
}

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!

Related blogs 🚀

Free eBooks:

Angular Directives In-Depth eBook Cover

JavaScript Array Methods eBook Cover

NestJS Build a RESTful CRUD API eBook Cover