Skip to content

Improve type inference for the listener callback #19

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Mar 8, 2021
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Improve type inference for the listener callback
Instead of using a generic Event type for the argument, the map of event types to the corresponding Event object types is used by the inference.

This is a BC break for projects specifying the generic types explicitly, as it changes the generic signature. For project relying on type inference, the inferred type becomes more specific.
  • Loading branch information
stof committed Feb 23, 2021
commit e54d96f4a0f338b11fdacc36fb0298b1026ac215
10 changes: 5 additions & 5 deletions index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -83,12 +83,12 @@ function safeClosest(event: Event, selector: string): Element | void {
*/
function delegate<
TElement extends Element = Element,
TEvent extends Event = Event
TEventType extends EventType = EventType
>(
base: EventTarget | Document | ArrayLike<Element> | string,
selector: string,
type: EventType,
callback: delegate.EventHandler<TEvent, TElement>,
type: TEventType,
callback: delegate.EventHandler<GlobalEventHandlersEventMap[TEventType], TElement>,
options?: boolean | AddEventListenerOptions
): delegate.Subscription {
// Handle Selector-based usage
Expand All @@ -101,7 +101,7 @@ function delegate<
const subscriptions = Array.prototype.map.call(
base,
(element: EventTarget) => {
return delegate<TElement, TEvent>(
return delegate<TElement, TEventType>(
element,
selector,
type,
Expand All @@ -127,7 +127,7 @@ function delegate<
const delegateTarget = safeClosest(event, selector);
if (delegateTarget) {
(event as any).delegateTarget = delegateTarget;
callback.call(baseElement, event as delegate.Event<TEvent, TElement>);
callback.call(baseElement, event as delegate.Event<GlobalEventHandlersEventMap[TEventType], TElement>);
}
};

Expand Down