0Pricing
TypeScript Academy · Lesson

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

  1. lib DOM types & querySelector (strict null checks)
  2. Event types, custom events; narrowing HTMLElement subtypes
  3. Working with FormData, URL, URLSearchParams
← Back to TypeScript Academy