Skip to content

Commit 2b4d3cc

Browse files
authored
Merge pull request #35 from dgraham/docs-add-readme-note-about-using-typescript-custom-overloads
docs: add readme note about using TypeScript custom overloads
2 parents 5bdca98 + 7f7e05b commit 2b4d3cc

File tree

1 file changed

+59
-0
lines changed

1 file changed

+59
-0
lines changed

README.md

+59
Original file line numberDiff line numberDiff line change
@@ -191,6 +191,65 @@ input.dispatchEvent(
191191
);
192192
```
193193

194+
## Adding TypeScript typed events
195+
196+
If you're using TypeScript, you can maintain a list of custom event names that map to their specific types, making it easier to write type-safe code while using delegated events. Add the following snippet to a `.d.ts` file in your local project and alter the contents of `CustomEventMap` to list all the well-known events in your project:
197+
198+
```typescript
199+
// events.d.ts
200+
interface CustomEventMap {
201+
'my-event:foo': {
202+
something: boolean
203+
}
204+
// When adding a new custom event to your code, add the event.name + event.detail type to this map!
205+
}
206+
207+
// Do not change code below this line!
208+
type CustomDelegatedEventListener<T> = (this: Element, ev: CustomEvent<T> & {currentTarget: Element}) => any
209+
210+
declare module 'delegated-events' {
211+
export function fire<K extends keyof CustomEventMap>(target: Element, name: K, detail: CustomEventMap[K]): boolean
212+
export function on<K extends keyof CustomEventMap>(
213+
name: K,
214+
selector: string,
215+
listener: CustomDelegatedEventListener<CustomEventMap[K]>
216+
): void
217+
}
218+
219+
declare global {
220+
interface Document {
221+
addEventListener<K extends keyof CustomEventMap>(
222+
type: K,
223+
listener: (this: Document, ev: CustomEvent<CustomEventMap[K]>) => unknown,
224+
options?: boolean | AddEventListenerOptions
225+
): void
226+
}
227+
interface HTMLElement {
228+
addEventListener<K extends keyof CustomEventMap>(
229+
type: K,
230+
listener: (this: HTMLElement, ev: CustomEvent<CustomEventMap[K]>) => unknown,
231+
options?: boolean | AddEventListenerOptions
232+
): void
233+
}
234+
}
235+
```
236+
237+
Now TypeScript is able to type-check your events in both `delegated-events` callsites and the standard `addEventListener` callsites:
238+
239+
```typescript
240+
fire(document.body, 'my-event:foo', {something: true})
241+
on('my-event:foo', 'body', event => {
242+
event.detail.something // typescript knows this is a boolean
243+
})
244+
document.addEventListener('my-event:foo', event => {
245+
event.detail.something // typescript knows this is a boolean
246+
})
247+
document.body.addEventListener('my-event:foo', event => {
248+
event.detail.something // typescript knows this is a boolean
249+
})
250+
```
251+
252+
194253
## Browser support
195254
196255
- Chrome

0 commit comments

Comments
 (0)