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
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 ?
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
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With