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

如何在TypeScript中为HTMLElement的attributes扩展新属性

解决方案

你可以通过嵌套交叉类型,精准修改HTMLElement的attributes属性类型,无需声明新类型或使用any:

const retyped = this.element.nativeElement as HTMLElement & {
  attributes: NamedNodeMap & { banana: string }
};

这样断言后,访问retyped.attributes.banana就不会触发类型错误了——TypeScript会识别到attributes既保留了原NamedNodeMap的所有特性,又新增了banana字符串属性。

原理是:交叉类型&可以在不修改原类型定义的前提下,对目标类型的某个子属性进行扩展。这里我们针对HTMLElement的attributes字段,将其与包含banana属性的对象类型交叉,既保留了原生NamedNodeMap的类型信息,又添加了自定义属性的类型声明。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.15 15:34:51