共计 1145 个字符,预计需要花费 3 分钟才能阅读完成。
Typescript 在 TS 文件里使用 document.getElementsByClassName 报错:
Type ‘Element’ is missing the following properties from type ‘HTMLElement’: accessKey, accessKeyLabel, autocapitalize, dir, and 116 more.
分析与解决:
ts 在使用 document.getElementsByClassName,document.querySelector 的时候,获取到的节点类型都是 Element 类型,而 innerText,innerHTML,以及 document.write,document.createElement,document.getElementById 都是只能在 HTMLElement 类型上进行使用的。
查阅 TS 对应源码:lib.dom.d.ts
getElementById(elementId: string): HTMLElement | null;
/** Returns a HTMLCollection of the elements in the object on which the method was invoked (a document or an element) that have all the classes given by classNames. The classNames argument is interpreted as a space-separated list of classes. */
getElementsByClassName(classNames: string): HTMLCollectionOf;
如果要得到 HTMLElement 类型可以使用 document.getElementById,此时就可以正常使用了。
如我的源码 food 这个类声明的 ele 的类型是:HEMLElement 类型,所有不能用 getElementsByClassName。否则类型不匹配就会报错。
修改:
this.ele = document.getElementsByClassName(“food”)[0]!;
改成:this.ele = document.getElementById(“food”)!;
//index.ts
// 来一个食物类,代表 div 方块
class Food {
ele: HTMLElement;
constructor() {this.ele = document.getElementById("food")!;
}
}
原文地址: ‘Element‘is missing the following properties from type‘HTMLElement‘: accessKey, accessKeyLabel