欢迎光临散文网 会员登陆 & 注册

报错Property 'className' does not exist on type 'EventTarget'.的一种解

2022-10-20 22:32 作者:LogByMax  | 我要投稿

(认知有限,如有不妥,还望告知,欢迎讨论。)

问题产生背景

在写前端的过程中,我想要监听鼠标在界面上的点击,于是写了下面的代码

代码运行顺利,但是在GitHub上的规范检查中className这边出现报错

Property 'className' does not exist on type 'EventTarget'.


解决方法

通过查阅[1]的资料发现,由于EventTarget不是继承自Element类型,所以typescript不能成功识别class和id这些属性。

所以这里使用类型断言将event.target的类型明确指明为Element即可



=END=

=reference=

[1]https://www.designcise.com/web/tutorial/how-to-fix-property-does-not-exist-on-type-eventtarget-typescript-error

[2]https://www.typescriptlang.org/docs/handbook/2/everyday-types.html#type-assertions


报错Property 'className' does not exist on type 'EventTarget'.的一种解的评论 (共 条)

分享到微博请遵守国家法律