Tag name of the Element representation of target
.
Element or EventTarget.
Element type of specified target
.
InvalidElementError
if specified target
is null
or undefined
.
Valid EventTarget
function handleButtonClick(event: MouseEvent): void {
// We know this is an `HTMLButtonElement` because the event listener was
// attached to a `<button>` and `currentTarget` is therefore a button:
const buttonElement = asElement<"button">(event.currentTarget);
}
Invalid EventTarget
function handleButtonClick(event: MouseEvent): void {
// We're telling TypeScript this is an `<input>` when it's actually a
// button:
const element = asElement<"input">(event.currentTarget);
// TypeScript will _not_ complain about this, but you'll get an error:
console.log(element.valueAsNumber);
}
Returns an element with tag name
TN
for the specifiedtarget
.This differs from
toElement
in that it will never returnnull
, only the specified element type, and it only accepts an Element or EventTarget as input.If you specify a
null
orundefined
input, the function throws rather than returnsnull
.This function is useful for getting the EventTarget from an Event as a specific element type without needing to use a non-null assertion. In some cases, you know exactly what type of element will be associated with an Event and you want to assert it as such.
With this function, you are telling TypeScript what the element is, even if the type you pass into the generic is incorrect. If you try to access properties only available on an
HTMLButtonElement
when the Element or EventTarget you passed in is anHTMLDivElement
, you're going to get a runtime error.