You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Angular中使用(blur)事件时$event的正确TypeScript类型是什么?

Angular中使用(blur)事件时$event的正确TypeScript类型是什么?

嘿,这个问题我写Angular代码的时候也纠结过,其实答案很简单——你应该用FocusEvent来替代any类型!

当Angular里的输入框触发(blur)事件时,传递的$event本质上就是浏览器原生的焦点事件对象,对应TypeScript里的FocusEvent类型。用这个类型既能获得完整的类型提示,又能避免any带来的类型不安全问题。

给你修改后的代码参考:

HTML部分不用调整:

<input type="text" (blur)="onBlur($event)" />

TypeScript部分修正类型定义:

export class AngularComponent {
  public onBlur(event: FocusEvent) {
    // 这里要注意:event.target默认是EventTarget类型,没有value属性
    // 所以需要把它断言成HTMLInputElement,才能安全访问输入框的value
    const value = (event.target as HTMLInputElement).value;
    // 接下来就可以放心执行其他逻辑啦
  }
}

为什么要做这个断言呢?因为FocusEvent的target属性可能指向任何DOM元素,TypeScript没法确定它就是输入框,所以我们手动告诉它这个目标元素是HTMLInputElement,这样访问value就不会有类型报错了。

备注:内容来源于stack exchange,提问作者David Boothe

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.16 09:10:28