Event types, custom events; narrowing HTMLElement subtypes
Handle DOM events with correct types, create CustomEvent payloads, and narrow HTMLElement subtypes safely.
Intro
Goal: Add typed event listeners, narrow elements safely, and emit CustomEvent with payloads.
- Event types (MouseEvent, KeyboardEvent, InputEvent)
- Narrow target/currentTarget with instanceof
- CustomEvent detail payloads
Typed listeners
Listener signatures are typed by event name: click → MouseEvent, keydown → KeyboardEvent. Add explicit annotations for clarity.
const btn = document.querySelector("#btn");
if (btn) {
btn.addEventListener("click", (ev: MouseEvent) => {
console.log("x=", ev.clientX, "y=", ev.clientY);
});
}
window.addEventListener("keydown", (ev: KeyboardEvent) => {
console.log("key=", ev.key);
});All lessons in this course
- lib DOM types & querySelector (strict null checks)
- Event types, custom events; narrowing HTMLElement subtypes
- Working with FormData, URL, URLSearchParams