11

Why we are using:

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

instead of:

document.getElementById("ipv").value;

?

cezn
  • 2,705
  • 11
  • 16
  • 1
    `getElementById` returns an `Element` ... an `Element` does not have a `value` – Jaromanda X Sep 14 '18 at 06:14
  • 2
    [This answer](https://stackoverflow.com/a/12989808/3991628) should clarify things a bit. The gist of it is that typescript has no way of knowing that the element is an `HTMLInputElement` rather than a generic `HTMLElement` unless you tell it so. An `HTMLElement` doesn't have a `value` property, but an `HTMLInputElement` does, so it needs to be cast to that type. – Christopher Bradshaw Sep 14 '18 at 06:14

2 Answers2

19

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;
cooldave
  • 321
  • 1
  • 11
13

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.

BoltClock
  • 700,868
  • 160
  • 1,392
  • 1,356