• Returns an element with tag name TN for the specified target.

    Note

    This differs from toElement in that it will never return null, only the specified element type, and it only accepts an Element or EventTarget as input.

    If you specify a null or undefined input, the function throws rather than returns null.

    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.

    Warning

    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 an HTMLDivElement, you're going to get a runtime error.

    Type Parameters

    • TN extends TagName = "*"

      Tag name of the Element representation of target.

    Parameters

    • target: undefined | null | ElementLike<TN>

      Element or EventTarget.

    Returns ElementOf<TN>

    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);
    }