why we are using HTMLInputElement in typescript?

Why we are using:

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

instead of:

document.getElementById("ipv").value;

?

Upvotes: 13

Views: 35458

Answers (2)

cooldave
cooldave

Reputation: 341

The function getElementById returns object with type HTMLElement.

From 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 type is the base type for the other tag types of the DOM. For example, the type HTMLInputElement extends HTMLElement and have the property value that the type HTMLElement doesn't have.

From lib.dom.d.ts:

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

Since HTMLInputElement extends HTMLElement, the next lines can compile:

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

Upvotes: 21

BoltClock
BoltClock

Reputation: 723688

document.getElementById() won't be able to return a specific element type since it doesn't know in advance what that element will be, so you need to cast the result as an HTMLInputElement after the fact so that the value property of that class can be recognized.

Upvotes: 15

Related Questions