Skip to content
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

Make it more strongly-typed when used with TypeScript #25

Merged
merged 4 commits into from
Apr 10, 2021
Merged
Show file tree
Hide file tree
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
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"
}
}