Repository: TypeScript
Issue: Add type to retrieve valid events of an EventTarget
Labels: Suggestion,Awaiting More Feedback

<!-- 🚨 STOP 🚨 𝗦𝗧𝗢𝗣 🚨 𝑺𝑻𝑶𝑷 🚨

Half of all issues filed here are duplicates, answered in the FAQ, or not appropriate for the bug tracker.

Please help us by doing the following steps before logging an issue:
  * Search: https://github.com/Microsoft/TypeScript/search?type=Issues
  * Read the FAQ, especially the "Common Feature Requests" section: https://github.com/Microsoft/TypeScript/wiki/FAQ

-->

## Search Terms

<!-- List of keywords you searched for before creating this issue. Write them down here so that others can find this suggestion more easily -->

EventListener, EventMap, EventTarget

## Suggestion

<!-- A summary of what you'd like to see added or changed -->

There should a type to retrieve valid event names and listeners for a given `EventTarget`. `Window` has the following method:

```ts
addEventListener<K extends keyof WindowEventMap>(type: K, listener: (this: Window, ev: WindowEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;
```

Every `EventTarget` should have its own corresponding `EventMap` (even if no special event types are available for a given target, thus, resulting in an empty object). The `EventMap` of a given `EventTarget` could be retrieved as follows:

```ts
type WindowEventMap = EventMap<Window>;
type DocumentEventMap = EventMap<Document>;
type AudioNodeEventMap = EventMap<AudioNode>; // Empty interface
// ...
```

## Use Cases

<!--
What do you want to use this for?
What shortcomings exist with current approaches?
-->

I tried creating a function which encapsulates an event for easier [lifecycle management with React Hooks](https://reactjs.org/docs/hooks-effect.html#effects-with-cleanup):

```ts
export function managedEventListener<T extends EventTarget, K extends string>(
  target: T,
  type: K,
  callback: EventListener,
  options?: AddEventListenerOptions,
) {
  target.addEventListener(type, callback, options);
  return () => {
    target.removeEventListener(type, callback, options);
  };
}
```

Unfortunately, `EventListener` gives no proper IntelliSense and I had to use the `as EventListener` syntax like below, as suggested in #28357:

```ts
useEffect(
  () =>
    managedEventListener(window, 'deviceorientation', ((
      event: DeviceOrientationEvent,
    ) => {
      setOrientation(event);
    }) as EventListener),
  [],
);
```

My goal was to simplify the syntax to the following, with proper type inference:

```ts
useEffect(
  () =>
    managedEventListener(window, 'deviceorientation', event => {
      setOrientation(event);
    }),
  [],
);
```

Using [conditional types](https://www.typescriptlang.org/docs/handbook/release-notes/typescript-2-8.html#conditional-types), I was able to achieve the syntax above by replacing `EventListener` with a specialized `EventListenerCallback` type which extracts values from the 2 most commonly used event maps, namely `WindowEventMap` and `DocumentEventMap`:

```ts
type ExtractFrom<T, K> = K extends keyof T ? T[K] : never;
export type EventListenerCallback<T, K> = T extends Window
  ? (event: ExtractFrom<WindowEventMap, K>) => any
  : (T extends Document
      ? (event: ExtractFrom<DocumentEventMap, K>) => any
      : EventListener);
```

The new code for `managedEventListener` was born:

```ts
export function managedEventListener<T extends EventTarget, K extends string>(
  target: T,
  type: K,
  callback: EventListenerCallback<T, K>,
  options?: AddEventListenerOptions,
) {
  target.addEventListener(type, callback, options);
  return () => {
    target.removeEventListener(type, callback, options);
  };
}
```

## Examples

<!-- Show how this would be used and what the behavior would be -->

The code above could be greatly simplified by introducing the aforementioned `EventMap<EventTarget>` type:

```ts
export function managedEventListener<T extends EventTarget, K extends keyof EventMap<T>>(
  target: T,
  type: K,
  callback: (this: T, ev: EventMap<T>[K]) => any,
  options?: AddEventListenerOptions,
) {
  target.addEventListener(type, callback, options);
  return () => {
    target.removeEventListener(type, callback, options);
  };
}
```

## Checklist

My suggestion meets these guidelines:

* [x] This wouldn't be a breaking change in existing TypeScript/JavaScript code
* [x] This wouldn't change the runtime behavior of existing JavaScript code
* [x] This could be implemented without emitting different JS based on the types of the expressions
* [x] This isn't a runtime feature (e.g. library functionality, non-ECMAScript syntax with JavaScript output, etc.)
* [x] This feature would agree with the rest of [TypeScript's Design Goals](https://github.com/Microsoft/TypeScript/wiki/TypeScript-Design-Goals).