Reputation: 13
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
Reputation: 482
Why TypeScript is complaining:
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.
.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