‘Element‘ is missing the following properties from type ‘HTMLElement‘: accessKey, accessKeyLabel

16,070次阅读
没有评论

共计 1145 个字符,预计需要花费 3 分钟才能阅读完成。

Typescript 在 TS 文件里使用 document.getElementsByClassName 报错:

Type ‘Element’ is missing the following properties from type ‘HTMLElement’: accessKey, accessKeyLabel, autocapitalize, dir, and 116 more.

‘Element‘is missing the following properties from type‘HTMLElement‘: accessKey, accessKeyLabel

分析与解决:

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

    正文完
     0
    Yojack
    版权声明:本篇文章由 Yojack 于2024-10-02发表,共计1145字。
    转载说明:
    1 本网站名称:优杰开发笔记
    2 本站永久网址:https://yojack.cn
    3 本网站的文章部分内容可能来源于网络,仅供大家学习与参考,如有侵权,请联系站长进行删除处理。
    4 本站一切资源不代表本站立场,并不代表本站赞同其观点和对其真实性负责。
    5 本站所有内容均可转载及分享, 但请注明出处
    6 我们始终尊重原创作者的版权,所有文章在发布时,均尽可能注明出处与作者。
    7 站长邮箱:laylwenl@gmail.com
    评论(没有评论)