[Typescript] Typing “this” and “noImplicitThis”

See the following example:

const elem = document.querySelector('.click');

function handleClick(event: Event) {
  event.preventDefault();
  console.log(this);
}

elem.addEventListener('click', handleClick, false);

When we print the 'this' keyword, we can see that it point <a class="click">click</a> tag.

The code is working, but one problem is that 'this' keyword has type 'any'.

To avoid this problem in runtime, we add 'noImplicitThis': true in tsconfig.json

After enable it, we can see VSCode show the type error for us.

To fix this issue: 

function handleClick(this: HTMLAnchorElement, event: Event) {
  event.preventDefault();
  console.log(this);
}

Now typescript also understand that 'this' is typeof HTMLAnchorElement.

原文地址:https://www.cnblogs.com/Answer1215/p/13752649.html