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

将JS代码转为TS时,事件监听中detail的正确类型是什么?

解决TypeScript中CustomEvent的detail类型报错问题

默认的Event类型并不包含detail属性,这个属性是**自定义事件(CustomEvent)**特有的,所以你需要给监听函数的参数指定正确的类型:

方法一:定义detail的接口(推荐,类型更清晰)

先声明一个接口来描述detail的结构:

interface TimeDetail {
  hour: number;
  minutes: number;
  type: string;
}

然后在监听事件时,把参数类型指定为CustomEvent<TimeDetail>:

acceptEvent.addEventListener("accept", ({ detail: { hour, minutes, type } }: CustomEvent<TimeDetail>) => {
  this.time = `${hour}:${minutes} ${type}`;
});

方法二:内联泛型类型

如果不想单独定义接口,也可以直接在CustomEvent的泛型中指定detail的结构:

acceptEvent.addEventListener("accept", ({ detail: { hour, minutes, type } }: CustomEvent<{ hour: number; minutes: number; type: string }>) => {
  this.time = `${hour}:${minutes} ${type}`;
});

这样TypeScript就能正确识别detail属性,同时校验内部字段的类型,解决报错问题。

内容的提问来源于stack exchange,提问作者iamneaz

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.13 22:05:29