[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 @   Zhentiw  阅读(13)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· AI技术革命,工作效率10个最佳AI工具
历史上的今天:
2021-12-30 [React Typescript 2022] Use TypeScript to Type a React Class Component
2021-12-30 [React Typescript 2022] Type a Radio Button Component in React using TypeScript
2020-12-30 [Java] Primitive Stream
2020-12-30 [Java] Stream Intro example
2020-12-30 [Java] Collections Intro example
2018-12-30 [PWA] Disable Text Selection and Touch Callouts in a PWA on iOS
2018-12-30 [PWA] Customize the Splash Screen of a PWA built with create-react-app
点击右上角即可分享
微信分享提示