Open
Description
Checking the type of an element via element.tagName === 'name'
doesn't give you type guard and you have to use optional chain (or !
a.k.a. Typescript's non-null assertion operator) if the element can be undefined
or null
.
Some elements have a corresponding JavaScript interface (e.g. HTMLImageElement
for <img>
), one can also use instanceof
to check the element type without the aforementioned shortcomings.
An real life example is: 574d442
(#5036)
Fail
if (event.target.parentElement?.tagName === 'img') {
return (target as HTMLImageElement).src
}
Pass
if (event.target.parentElement instanceof HTMLImageElement) {
return target.src
}