microsoft / microsoft/TypeScript

Add type to retrieve valid events of an EventTarget

Abierto
#33,047 6 comentarios 21 reacciones 0 asignados Ver en GitHub

Nadie ha tomado este issue todavía.

Awaiting More Feedback Suggestion
Lenguaje dominante
Go
Estrellas
111k
Forks
14.4k
Merge medio
1 d 19 h
PR fusionados (30 d)
117

Descripción

Search Terms

EventListener, EventMap, EventTarget

Suggestion

There should a type to retrieve valid event names and listeners for a given EventTarget. Window has the following method:

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:

type WindowEventMap = EventMap<Window>;
type DocumentEventMap = EventMap<Document>;
type AudioNodeEventMap = EventMap<AudioNode>; // Empty interface
// ...

Use Cases

I tried creating a function which encapsulates an event for easier lifecycle management with React Hooks:

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:

useEffect(
  () =>
    managedEventListener(window, 'deviceorientation', ((
      event: DeviceOrientationEvent,
    ) => {
      setOrientation(event);
    }) as EventListener),
  [],
);

My goal was to simplify the syntax to the following, with proper type inference:

useEffect(
  () =>
    managedEventListener(window, 'deviceorientation', event => {
      setOrientation(event);
    }),
  [],
);

Using 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:

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:

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

The code above could be greatly simplified by introducing the aforementioned EventMap<EventTarget> type:

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:

  • This wouldn't be a breaking change in existing TypeScript/JavaScript code
  • This wouldn't change the runtime behavior of existing JavaScript code
  • This could be implemented without emitting different JS based on the types of the expressions
  • This isn't a runtime feature (e.g. library functionality, non-ECMAScript syntax with JavaScript output, etc.)
  • This feature would agree with the rest of TypeScript's Design Goals.

Guía de contribución

Abrir la guía de contribución

Primeros pasos

  1. Lee el issue completo y luego la guía de contribución del proyecto.
  2. Comenta en el issue que vas a ocuparte — evita que dos personas hagan lo mismo.
  3. Haz un fork del repositorio y trabaja en una rama.
  4. Abre un pull request que haga referencia al número del issue.

Línea de trabajo

Comienza revisando los tipos existentes de listeners de eventos de EventTarget, incluidos WindowEventMap y DocumentEventMap, y compáralos con los ejemplos propuestos de EventMap. Determina si cada EventTarget puede exponer un mapa de eventos correspondiente y cómo deben inferirse los nombres de eventos genéricos y los parámetros del listener. Se considera terminado cuando el tipo solicitado admite el uso mostrado de managedEventListener sin casts.

Escrito por el modelo de indexación a partir del texto del issue.

Evaluación

Stack tecnológico
typescript
Área
compilers
Tipo de issue
Nueva funcionalidad
Dificultad
5/5
Tiempo estimado
Más de una semana
Estado de actividad
Estancado
Claridad
Bastante claro
Aptitud para principiantes
25/100

Recibe los nuevos issues en tu correo

Un resumen breve de issues de GitHub para principiantes.