Typed DOM Listeners With HTMLElementEventMap
A listener helper keyed by HTMLElementEventMap narrows the callback event type from the event name and returns an unbind function for exact cleanup.
Code
// Constrain listeners with the DOM's own event map (HTMLElementEventMap):
// a misspelled event name or wrong callback param type fails at compile time
function on<K extends keyof HTMLElementEventMap>(
target: HTMLElement,
type: K,
handler: (event: HTMLElementEventMap[K]) => void,
): () => void {
target.addEventListener(type, handler);
return () => target.removeEventListener(type, handler);
}
const form = document.querySelector<HTMLFormElement>('#signup');
const email = document.querySelector<HTMLInputElement>('#email');
if (form && email) {
// K narrows to 'input': the callback param is InputEvent, email.value reads without assertions
const stopInput = on(email, 'input', () => {
console.log('input value length:', email.value.length);
});
// K narrows to 'submit': the callback param is SubmitEvent, preventDefault is callable
const stopSubmit = on(form, 'submit', (event) => {
event.preventDefault();
console.log('submit blocked, email was:', email.value);
});
// on(email, 'clik', ...) - the misspelled name is a compile error, callback param types stay checked
// The returned unsubscribe removes exactly its own listener, preventing dangling ones after unmount
setTimeout(() => {
stopInput();
stopSubmit();
console.log('listeners removed');
}, 5000);
}How the snippet works
Typed DOM Listeners With HTMLElementEventMap is built around the function on.
Caveats
documentexist only in browsers — a Node runtime has no shims for them out of the box.
Applying it
The demo output is labeled (input value length:, submit blocked, email was:, listeners removed), so every printed line traces back to the operation behind it.
Statements that matter
return () => target.removeEventListener(type, handler);
const stopSubmit = on(form, 'submit', (event) => {
event.preventDefault();
console.log('submit blocked, email was:', email.value);
});
const stopInput = on(email, 'input', () => {
console.log('input value length:', email.value.length);
});
Interactive Tools for This Topic
DOM Event Propagation VisualizerVisualize DOM event capturing, targeting, and bubbling phases in real time. Toggle stopPropagation and stopImmediatePropagation to see how events traverse the tree.JSON to Zod Schema ConverterInfer typed Zod z.object schemas from JSON payloads locally, supporting nested objects, merged array shapes, enums, nullable fields, and JSDoc comments.JSON Schema ValidatorValidate JSON data against a JSON Schema definition and get detailed error reports. Supports type checking, required fields, and common constraint validation.JSONL / NDJSON InspectorValidate NDJSON and JSON Lines line-by-line, pinpoint syntax errors by line number, analyze key frequencies and types, and export a pretty JSON array.
FAQ
- Does Typed DOM Listeners With HTMLElementEventMap run in plain Node.js?
- No — it touches `document`, which exist only in the browser. Run it in a page (or the DevTools console) instead of a bare Node process.
Report a problem with this exampleOpens a pre-filled issue on GitHub.