Event Handling in TypeScript
Click Events
A click handler's event parameter is typed as MouseEvent, which gives you access to coordinates and modifier-key state (like event.shiftKey) with full autocomplete instead of an untyped generic Event.
Example: Click Events
const button = document.createElement("button");
button.addEventListener("click", (event: MouseEvent) => {
console.log("Clicked at", event.clientX, event.clientY);
});
button.dispatchEvent(new MouseEvent("click", { clientX: 10, clientY: 20 }));
Keyboard Events
Keyboard event handlers receive a KeyboardEvent, whose .key and .code properties let you distinguish exactly which key was pressed, which MouseEvent and other event types simply don't expose.
Example: Keyboard Events
document.addEventListener("keydown", (event: KeyboardEvent) => {
console.log("Key pressed:", event.key);
});
document.dispatchEvent(new KeyboardEvent("keydown", { key: "Enter" }));
Input Events
Input events on form fields are typed as Event with the target narrowed to something like HTMLInputElement, since the base Event type alone doesn't know it's attached to an input with a .value property.
Example: Input Events
const input = document.createElement("input");
input.addEventListener("input", (event: Event) => {
const target = event.target as HTMLInputElement;
console.log("Value is now:", target.value);
});
input.value = "hi";
input.dispatchEvent(new Event("input"));
Event Targets
event.target is typed generically as EventTarget | null, so reading a DOM-specific property off it requires narrowing or casting to the concrete element type you expect the event to have actually come from.
Example: Event Targets
document.addEventListener("click", (event: Event) => {
const target = event.target as HTMLElement | null;
console.log("Clicked element:", target?.tagName);
});
document.dispatchEvent(new MouseEvent("click"));
Removing Event Listeners
removeEventListener requires passing the exact same function reference that was registered with addEventListener, so an inline anonymous arrow function can never be removed later — store the handler in a named variable if you'll need to detach it.
Example: Removing Event Listeners
function handleClick() {
console.log("Handled");
}
const button = document.createElement("button");
button.addEventListener("click", handleClick);
button.removeEventListener("click", handleClick);
console.log("Listener removed using the same named function reference");
Chapter Quiz — Complete all 6 topics to unlock
0/6 topics done
Complete these topics first: