This keyword in typescript

Typing «this» Keyword in TypeScript

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

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.

Learn TypeScript the right way.

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

Источник

TypeScript, event handlers in the DOM, and the this keyword

TypeScript, event handlers in the DOM, and the this keyword

this in JavaScript is a magic keyword for: «whichever object a given function runs in». Consider the following object and its nested function:

const person =  name: "Jule", printName: function()  console.log(this.name); > >; 

When I call person.printName() , this will point to the person object. this is everywhere in JavaScript, including event handler functions in the DOM.

What are event handlers in JavaScript?

The Document Object Model is a convenient representation of every element in an HTML page. Browsers keep this structure in memory and expose a lot of methods for interacting with the DOM.

HTML elements in the DOM are not static. They are connected to a primordial object named EventTarget which lends them three methods:

Whenever an HTML element is clicked, the most simple case, an event is dispatched. Developers can intercept these events (JavaScript engines are event-driven) with an event listener.

Event listeners in the DOM have access to this because the function runs in the context object who fired up the event (an HTML element most of the times). Consider the following snippet:

const button = document.querySelector("button"); button.addEventListener("click", handleClick); function handleClick()  console.log("Clicked!"); this.removeEventListener("click", handleClick); > 

Here removeEventListener is called on the HTML button who triggered the click event. Now let’s see what happens when we convert this code to TypeScript.

When converting our code to TypeScript the IDE and the compiler will complain with two errors:

error TS2531: Object is possibly 'null'. error TS2683: 'this' implicitly has type 'any' because it does not have a type annotation. 

We can get rid of the first error with optional chaining, landed in TypeScript > 3.7:

const button = document.querySelector("button"); // optional chaining button?.addEventListener("click", handleClick); function handleClick()  console.log("Clicked!"); this.removeEventListener("click", handleClick); > 

For the second error to go away instead, this must appear as the first parameter in the handler signature, with the appropriate type annotation. HTMLElement is enough in this case:

const button = document.querySelector("button"); button?.addEventListener("click", handleClick); function handleClick(this: HTMLElement)  console.log("Clicked!"); this.removeEventListener("click", handleClick); >  

You might have guessed how the «trick» is applicable to any function dealing with this , not necessarily an event handler (don’t mind any here):

function aGenericFunction(this: any, key: string)  return this.doStuff(key); > const aFictionalObject =  first: "a", second: "b", doStuff: function(str: string)  return `$this.first> $str>`; > >; aGenericFunction.call(aFictionalObject, "appendMe"); 

Thanks for reading and stay tuned!

SOCIAL

COURSES AND BOOKS

ON-SITE WORKSHOP: JAVASCRIPT AND FRONTEND TESTING

Learn everything you need to know to test and write solid, modular, maintainable frontend code that «stands the test of time».

Get in touch for the full course curriculum and 2023 availability.

Decoupled Django

Decoupled Django

Refactoring to React Hooks

Refactoring to React Hooks liveProject

The Little JavaScript Book

The Little JavaScript Book

Valentino Gagliardi

Hi! I’m Valentino! I’m a freelance consultant with a wealth of experience in the IT industry. I spent the last years as a frontend consultant, providing advice and help, coaching and training on JavaScript and React. Let’s get in touch!

More from the blog:

SOCIAL

COURSES AND BOOKS

ON-SITE WORKSHOP: JAVASCRIPT AND FRONTEND TESTING

Learn everything you need to know to test and write solid, modular, maintainable frontend code that «stands the test of time».

Get in touch for the full course curriculum and 2023 availability.

Источник

Читайте также:  Database used for php
Оцените статью