Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Argument of type 'Element' is not assignable to parameter of type 'HTMLElement'

Tags:

typescript

const labelEl: HTMLElement = document.createElement('label')
const isElOfNeededType = (el: HTMLElement): boolean =>
    ["INPUT", "TEXTAREA"].includes(el.tagName);

let result

if (isElOfNeededType(labelEl.nextElementSibling)) {
    result = true
}

Here's my playground: link

  1. Why am I getting this error on labelEl.nextElementSibling?

    Argument of type 'Element' is not assignable to parameter of type 'HTMLElement'

Doesn't HTMLElement extend Element?

2. (not really important, but would be glad if explained) Why does TS playground complains about [ ].includes whereas I've set Config -> Target = esnext ?

like image 694
avalanche1 Avatar asked Nov 25 '25 13:11

avalanche1


1 Answers

labelEl.nextElementSibling is of type Element. See the definition in Definitely Typed. So your code is trying to pass an Element where an HTMLElement is required.

As you say, HTMLElement extends Element, but this does mean you can pass an Element in place of an HTMLElement, because the Element may not have properties that an HTMLElement does. You could however pass an HTMLElement where an Element is expected, because an HTMLElement will have all the properties of an Element.

Seeing as you are only interested in the tagName property, which exists on Element I would just change your code to use Element.

const labelEl: HTMLElement = document.createElement('label')
const isElOfNeededType = (el: Element): boolean =>
    ["INPUT", "TEXTAREA"].includes(el.tagName);

let result

if (isElOfNeededType(labelEl.nextElementSibling)) {
    result = true
}
like image 146
Collierre Avatar answered Nov 27 '25 15:11

Collierre



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!