[Typescript] This type

Sometimes we have a free-standing function that has a strong opinion around what this will end up being, at the time it is invoked.

For example, if we had a DOM event listener for a button:

<button onClick="myClickHandler">Click Me!</button>

 In the following handler, thethis type is any.

 

Oh no! this is an any type. We sure don’t want to depend on disabled being a defined property without some degree of type safety. If we enable the compilerOptions.noImplicitThisflag in tsconfig.json, you’ll see a type checking error here

 

To address the problem, we need to give this function a this type

function myClickHandler(
  this: HTMLButtonElement,
  event: Event
) {
  this.disabled = true
}

myClickHandler(new Event('click')) // The 'this' context of type 'void' is not assignable to method's 'this' of type 'HTMLButtonElement'.

 

To resolve this issue, we need to manually bind:

function myClickHandler(
  this: HTMLButtonElement,
  event: Event
) {
  this.disabled = true
}

myClickHandler(new Event("click")) // not working

const myButton = document.getElementsByTagName("button")[0]           
const boundHandler: (event: Event) => void = myClickHandler.bind(myButton)
boundHandler(new Event("click")) // bound version: ok
myClickHandler.call(myButton, new Event("click")) // also ok

   

You can also enable strictBindApply

posted @ 2023-12-30 22:10  Zhentiw  阅读(10)  评论(0编辑  收藏  举报