[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.noImplicitThis
flag 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
分类:
TypeScript
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 阿里最新开源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