Heßaa Ahmad
Heßaa Ahmad

Reputation: 13

what is the type for this html element other that HTMLAnchorElement

I am trying to get type for an anchor which I select from DOM but always tell me that it doesn't contain properties of Anchor as download, charset and so on

interface myLinkType extends HTMLAnchorElement {}

const myLink: myLinkType(that gives error) = document.getElementById('mylink')

Upvotes: 0

Views: 1029

Answers (1)

Martin Jaskulla
Martin Jaskulla

Reputation: 482

Why TypeScript is complaining:

  • getElementById can return other elements than anchors. This is why the error message is: Type 'HTMLElement | null' is not assignable to type 'HTMLAnchorElement | null'. If you put id="mylink" on a button by accident, then the button will not have anchor properties such as charset etc. The error message is: Type 'HTMLElement' is missing the following properties from type 'HTMLAnchorElement': charset, coords, download, hreflang, and 21 more..
  • Also getElementById is not guaranteed to find an element. If it cannot find an element, it returns null.

TypeScript is trying to force your program to check if getElementById found an element and that this element is in fact an anchor before accessing these properties. This is done to prevent run time errors.

This works, because it can only return an anchor element:

const a: HTMLAnchorElement | null = document.querySelector('a#mylink')

Upvotes: 2

Related Questions