Skip to content

EventListener on a union of Element types should accept a specific event type as parameter #46819

Closed as not planned
@bennypowers

Description

@bennypowers

Bug Report

� Search Terms

HTMLElement, HTMLButtonElement, HTMLAnchorElement, HTMLElementEventNameMap, EventListener, MouseEvent, KeyboardEvent, Event, parameter, EventListenerOrEventListenerObject

� Version & Regression Information

  • This is the behavior in every version I tried, and I reviewed the FAQ for entries about strictFunctionTypes (this affects functions as well as methods)

⏯ Playground Link

Playground link with relevant code

� Code

document.createElement("button").addEventListener('click', onClick);
document.createElement("a").addEventListener('click', onClick);
const clicker = document.querySelector<HTMLAnchorElement|HTMLButtonElement>('#clicker');
// @ts-expect-error: should not error, but gives type error below
clicker?.addEventListener('click', onClick);
function onClick(e: MouseEvent) {}

� Actual behavior

Argument of type '(e: MouseEvent) => void' is not assignable to parameter of type 'EventListenerOrEventListenerObject'.
  Type '(e: MouseEvent) => void' is not assignable to type 'EventListener'.
    Types of parameters 'e' and 'evt' are incompatible.
      Type 'Event' is not assignable to type 'MouseEvent'.

� Expected behavior

No error, the parameter type MouseEvent should be inferred as congruent with the parameter type of EventListener

Metadata

Metadata

Assignees

No one assigned

    Labels

    Design LimitationConstraints of the existing architecture prevent this from being fixed

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions