【问题标题】:why we are using HTMLInputElement in typescript?为什么我们在打字稿中使用 HTMLInputElement?
【发布时间】:2019-02-18 21:40:59
【问题描述】:

我们为什么使用:

(document.getElementById("ipv") as HTMLInputElement).value;

代替:

document.getElementById("ipv").value;

?

【问题讨论】:

  • getElementById 返回 Element ... Element 没有 value
  • This answer 应该澄清一下。它的要点是打字稿无法知道该元素是HTMLInputElement,而不是通用的HTMLElement,除非你告诉它。 HTMLElement 没有 value 属性,但 HTMLInputElement 有,因此需要将其强制转换为该类型。

标签: javascript typescript


【解决方案1】:

document.getElementById() 将无法返回特定元素类型,因为它事先不知道该元素将是什么,因此您需要在事后将结果转换为 HTMLInputElement,以便 value可以识别该类的属性。

【讨论】:

    【解决方案2】:

    函数getElementById返回HTMLElement类型的对象。

    来自 lib.dom.d.ts:

     /**
     * Returns a reference to the first object with the specified value of the ID or NAME attribute.
     * @param elementId String that specifies the ID value. Case-insensitive.
     */
    getElementById(elementId: string): HTMLElement | null;
    

    HTMLElement 类型是 DOM 的其他标签类型的基本类型。 例如,HTMLInputElement 类型扩展了 HTMLElement 并具有 value 类型 HTMLElement 没有的属性。

    来自 lib.dom.d.ts:

    interface HTMLInputElement extends HTMLElement {
    ...
    /**
     * Returns the value of the data at the cursor's current position.
     */
    value: string;
    ...
    

    由于HTMLInputElement 扩展了HTMLElement,下一行可以编译:

    const inputTag = document.getElementById('name-input') as HTMLInputElement;
    const value = inputTag.value;
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-12-12
      • 1970-01-01
      • 1970-01-01
      • 2020-09-11
      • 2021-07-06
      • 2017-07-22
      • 2016-04-08
      • 2021-08-10
      相关资源
      最近更新 更多