为什么我们在打字稿中使用HTMLInputElement?

Mut*_*amy 2 javascript typescript

我们为什么使用:

(document.getElementById("ipv") as HTMLInputElement).value;
Run Code Online (Sandbox Code Playgroud)

代替:

document.getElementById("ipv").value;
Run Code Online (Sandbox Code Playgroud)

?

Bol*_*ock 7

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


coo*_*ave 5

该函数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;
Run Code Online (Sandbox Code Playgroud)

HTMLElementtype是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;
...
Run Code Online (Sandbox Code Playgroud)

由于HTMLInputElementextends HTMLElement,接下来的行可以编译:

const inputTag = document.getElementById('name-input') as HTMLInputElement;
const value = inputTag.value;
Run Code Online (Sandbox Code Playgroud)