Event Delegation Implementation in TypeScript
14-day free trial
Try SeekerPro free for 14 days.
Full access while you try it · then $15.99/mo · cancel anytime
Start your 14-day free SeekerPro trial →30-day money-back guarantee · Cancel anytime
Not checking a site today? Turn this topic into a ready to paste AI prompt, free →
Key Takeaways
- ✓Event Delegation runs in O(1) time and O(1) space, in TypeScript as in every other language.
- ✓Nothing exists at runtime; it is all lib.dom.d.ts. The declarations that matter here are Event.target typed EventTarget | null, HTMLElementEventMap (the reason addEventListener("click", ...) infers MouseEvent), DOMStringMap (dataset values are string | undefined, not string), and the four overloads of Element.closest.
- ✓The cast is what gets flagged. ev.target as HTMLElement compiles, weighs nothing at runtime, and is a lie the moment a click lands somewhere unexpected.
- ✓The TypeScript trap: Element.closest carries the overload closest<E extends Element = Element>(selectors: string): E | null.
- ✓Types erase, and the erasure is total: satisfies Record<string, SeatHandler> compiles away and leaves the object literal byte-identical, so the emitted delegate is what you would have hand-written.
What Event Delegation actually is
Event Delegation in TypeScript: what you actually reach for
TypeScript implementation
type SeatHandler = (seat: HTMLElement, ev: MouseEvent) => void;
// satisfies checks every value and still leaves the keys as a literal union.
const handlers = {
"seat.hold": (seat, ev) => seat.toggleAttribute("data-held", !ev.altKey),
"seat.release": (seat, ev) => { if (!ev.shiftKey) seat.removeAttribute("data-held"); },
} satisfies Record<string, SeatHandler>;
type SeatAction = keyof typeof handlers;
function isSeatAction(value: string | undefined): value is SeatAction {
return value !== undefined && Object.hasOwn(handlers, value);
}
export function delegate(hall: HTMLElement): () => void {
const onClick = (ev: MouseEvent): void => {
// Event.target is EventTarget | null in lib.dom. Narrow it, never cast it.
if (!(ev.target instanceof Element)) return;
// Deliberately NOT closest<HTMLElement>(...): that type argument is never
// checked against the selector. Narrow the result instead, which is also
// what rejects the SVGElement you get when the click hits an inline icon.
const seat = ev.target.closest("[data-action]");
if (!(seat instanceof HTMLElement) || !hall.contains(seat)) return;
const action = seat.dataset.action; // string | undefined
if (!isSeatAction(action)) return; // now a literal union
handlers[action](seat, ev);
};
hall.addEventListener("click", onClick);
return () => hall.removeEventListener("click", onClick);
}Think Your Code Is Clean? Let NexusBro QA It in 20 Seconds.
Paste your code. Click QA. Get an instant expert-level audit with fixes.
QA My Code FreeThe TypeScript-specific trap
Performance in TypeScript, beyond the O(1)
Real-World Applications
Interview Tips & Practice
Frequently Asked Questions
Which TypeScript type or library should I use for Event Delegation?
Nothing exists at runtime; it is all lib.dom.d.ts. The declarations that matter here are Event.target typed EventTarget | null, HTMLElementEventMap (the reason addEventListener("click", ...) infers MouseEvent), DOMStringMap (dataset values are string | undefined, not string), and the four overloads of Element.closest. EventListenerObject lets a class register itself through a handleEvent method rather than a bound arrow, which keeps this correct without .bind. satisfies on the action table preserves the literal key union while still type-checking every handler value.
What is the most common TypeScript mistake when implementing Event Delegation?
Element.closest carries the overload closest<E extends Element = Element>(selectors: string): E | null. The type argument is never compared against the selector, so closest<HTMLButtonElement>("[data-action]") is typed HTMLButtonElement | null whatever the selector really matched: a generic-shaped type assertion that --strict happily accepts, letting you write hit.disabled = true onto a div. The runtime half is just as sharp. An inline <svg> icon inside the seat makes ev.target an SVGElement, which passes instanceof Element but fails instanceof HTMLElement, and reading hit.offsetWidth off it yields undefined rather than throwing.
How does Event Delegation actually perform in TypeScript?
Types erase, and the erasure is total: satisfies Record<string, SeatHandler> compiles away and leaves the object literal byte-identical, so the emitted delegate is what you would have hand-written. Two things do survive into the output. Every instanceof guard you added for type safety is a real prototype-chain walk executed on each event, a cost the untyped version never pays for. And a plain enum emits a runtime IIFE plus a var; a const object with satisfies gives you the same literal union with no emitted object at all. Time complexity is O(1) and space is O(1).
Related Articles
Rather try before you buy?
Get the rest of the vault: every cheat sheet, guide and audit in SeekerPro, free for 14 days, then $15.99/mo. Cancel anytime. Daily usage limits apply.
Start my 14-day SeekerPro trialBefore paying for Devin, check its student and free-tier options on Noizz.
Is your site built to last?
Run a free QA audit and get your Site Health Score in seconds.
Check Your Site FreeNo signup required
Reader comments
No account needed. Share what worked, what did not, and what you would add.
Add your take below. A concrete tip, a result or a question helps the next reader most.