Skip to content

Commit

Permalink
Make it more strongly-typed when used with TypeScript (#25)
Browse files Browse the repository at this point in the history
  • Loading branch information
fregante authored Apr 10, 2021
1 parent ce9fe39 commit cceddeb
Show file tree
Hide file tree
Showing 2 changed files with 32 additions and 3 deletions.
30 changes: 28 additions & 2 deletions index.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
import type {ParseSelector} from 'typed-query-selector/parser';

export type EventType = keyof GlobalEventHandlersEventMap;
type GlobalEvent = Event;

Expand Down Expand Up @@ -82,7 +84,31 @@ function safeClosest(event: Event, selector: string): Element | void {
* Delegates event to a selector.
*/
function delegate<
TElement extends Element = Element,
Selector extends string,
TElement extends Element = ParseSelector<Selector, HTMLElement>,
TEventType extends EventType = EventType
>(
base: EventTarget | Document | ArrayLike<Element> | string,
selector: Selector,
type: TEventType,
callback: delegate.EventHandler<GlobalEventHandlersEventMap[TEventType], TElement>,
options?: boolean | AddEventListenerOptions
): delegate.Subscription;

function delegate<
TElement extends Element = HTMLElement,
TEventType extends EventType = EventType
>(
base: EventTarget | Document | ArrayLike<Element> | string,
selector: string,
type: TEventType,
callback: delegate.EventHandler<GlobalEventHandlersEventMap[TEventType], TElement>,
options?: boolean | AddEventListenerOptions
): delegate.Subscription;

// This type isn't exported as a declaration, so it needs to be duplicated above
function delegate<
TElement extends Element,
TEventType extends EventType = EventType
>(
base: EventTarget | Document | ArrayLike<Element> | string,
Expand All @@ -101,7 +127,7 @@ function delegate<
const subscriptions = Array.prototype.map.call(
base,
(element: EventTarget) => {
return delegate<TElement, TEventType>(
return delegate(
element,
selector,
type,
Expand Down
5 changes: 4 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "delegate-it",
"version": "2.0.2",
"version": "3.0.0-1",
"description": "Lightweight event delegation",
"keywords": [
"delegate",
Expand Down Expand Up @@ -43,5 +43,8 @@
"sinon": "^9.2.4",
"typescript": "^4.2.3",
"xo": "^0.38.2"
},
"dependencies": {
"typed-query-selector": "^2.4.1"
}
}

0 comments on commit cceddeb

Please sign in to comment.