【问题标题】:TypeScript complains about HTMLElement do not have value propertyTypeScript 抱怨 HTMLElement 没有 value 属性
【发布时间】:2017-05-20 17:07:42
【问题描述】:

TypeScript 抱怨 HTMLElement 没有 value 属性,但是当我在 JavaScript 中使用它时,它可以正常工作。

 var inputValue: HTMLElement = document.getElementById('input1');
 console.log(inputValue.value); // show error message

在 JavaScript 中, var inputValue= document.getElementById('input1'); 控制台.log(inputValue.value); // 它给了我输入元素的值

我能知道为什么 TypeScript 会抱怨吗?

【问题讨论】:

    标签: javascript typescript


    【解决方案1】:

    HTMLElement 没有 value 成员,HTMLInputElement 有。
    你需要输入 assert 它:

    var inputValue = document.getElementById('input1') as HTMLInputElement;
    console.log(inputValue.value); // should be ok
    

    编辑

    打字稿定义代表实际的 javascript dom 元素,在本例中为 HTMLElementHTMLInputElement

    【讨论】:

    • 感谢您的回答。为什么是 HTMLInputElement?
    • as 是从哪里来的? JavaScript 还是 TypeScript?
    • 查看修改后的答案
    猜你喜欢
    • 2018-05-18
    • 2019-12-18
    • 1970-01-01
    • 2020-11-21
    • 2021-07-02
    • 2018-03-16
    • 2021-11-07
    • 1970-01-01
    • 2019-12-05
    相关资源
    最近更新 更多