Skip to content
jshacks.dev
TypeScript

How to Type Event Handlers in TypeScript

Type DOM event handlers correctly: inferred listeners, event map types, currentTarget versus target, custom events, and the errors that point you to the fix.

7 min read
Summarize in AI
Flat illustration of one event fanning out to several listeners, with the TypeScript, Google Chrome, Node.js and Socket.io logos.

Event handlers are where DOM typing gets uncomfortable. The event object has a dozen possible shapes, event.target is not the element you think it is, and a custom event carries data the compiler has never heard of. This post shows how to type each case without reaching for any. It uses the DOM types that ship with TypeScript 6.x in lib.dom.d.ts, and they are unchanged in the TypeScript 7 native compiler, tsgo. For the underlying platform behavior, see MDN on the Event interface.

Step 1: Let addEventListener infer the event

When you call addEventListener with a literal event name, TypeScript looks the name up in a map and types the callback for you.

TypeScript
const button = document.querySelector("button");

button?.addEventListener("click", (event) => {
  console.log(event.clientX, event.button);
});
Text
120 0

The output assumes a click at horizontal position 120 with the primary button. The type of event is MouseEvent, because the "click" key in HTMLElementEventMap maps to it. If you mistype a property, the compiler tells you.

TypeScript
button?.addEventListener("click", (event) => {
  console.log(event.key);
});
Text
index.ts(4,23): error TS2339: Property 'key' does not exist on type 'MouseEvent'.

The lesson is to keep the handler inline, or to type it with the right interface when you pull it out.

Step 2: Type a handler you declare separately

A handler written as a standalone function has no context to infer from, so you annotate the parameter with the event interface.

TypeScript
function onKeyDown(event: KeyboardEvent): void {
  if (event.key === "Escape") {
    console.log("closing");
  }
}

document.addEventListener("keydown", onKeyDown);
Text
closing

Attach it to the wrong event and the compiler objects, because a keydown listener must accept a KeyboardEvent.

TypeScript
document.addEventListener("click", onKeyDown);
Text
index.ts(1,36): error TS2769: No overload matches this call.
  Overload 1 of 2, '(type: "click", listener: (this: Document, ev: MouseEvent) => any, options?: boolean | AddEventListenerOptions | undefined): void', gave the following error.
    Argument of type '(event: KeyboardEvent) => void' is not assignable to parameter of type '(this: Document, ev: MouseEvent) => any'.
      Types of parameters 'event' and 'ev' are incompatible.
        Type 'MouseEvent' is missing the following properties from type 'KeyboardEvent': altKey, code, ctrlKey, isComposing, and 9 more.

Read the last line first. It names both types, and it is almost always enough to find the mismatch.

Step 3: Understand target and currentTarget

event.target is the element that triggered the event, which may be a child of the one you listened on. event.currentTarget is the element the listener is attached to. In the DOM typings, both are typed EventTarget | null, the broadest possible type, because the compiler cannot know what was clicked.

TypeScript
const input = document.querySelector("input");

input?.addEventListener("input", (event) => {
  console.log(event.target.value);
});
Text
index.ts(4,23): error TS18047: 'event.target' is possibly 'null'.

Even without the null, EventTarget has no value. There are two fixes, and the better one depends on what you know.

If you attached the listener to the element you care about, you already hold a typed reference to it. Read the value from that variable instead of the event.

TypeScript
const input = document.querySelector("input");

input?.addEventListener("input", () => {
  console.log(input.value);
});
Text
hello

Inside the callback, input is narrowed to HTMLInputElement, because the optional chain proved it exists. Note that event.currentTarget does not help here: the DOM typings declare it as EventTarget | null whatever you attached the listener to, and the browser resets it to null after the handler yields, for example after an await. A listener written as a function expression does get a typed this, as in function (this: HTMLInputElement) {}, but a closure over the variable is simpler and works with arrow functions.

If you use event delegation, with one listener on a parent and many children, target is the right property and you must narrow it.

TypeScript
const list = document.querySelector("ul");

list?.addEventListener("click", (event) => {
  const target = event.target;
  if (target instanceof HTMLLIElement) {
    console.log(target.textContent);
  }
});
Text
Second item

An instanceof check narrows EventTarget to a real element type and also protects you from clicks on text nodes or padding. We prefer it to a cast like event.target as HTMLLIElement, which silences the compiler and fails at run time when the assumption is wrong.

Step 4: Type form events

A submit listener receives a SubmitEvent. The same rule applies as above: do not expect currentTarget to be typed as the form.

TypeScript
const form = document.querySelector("form");

form?.addEventListener("submit", (event) => {
  event.preventDefault();
  const data = new FormData(event.currentTarget);
  console.log(data.get("email"));
});
Text
index.ts(5,31): error TS2345: Argument of type 'EventTarget | null' is not assignable to parameter of type 'HTMLFormElement | undefined'.

The reliable fix is to use the variable you already have.

TypeScript
const form = document.querySelector("form");

form?.addEventListener("submit", (event) => {
  event.preventDefault();
  const data = new FormData(form);
  console.log(data.get("email"));
});
Text
[email protected]

The closure over form is typed HTMLFormElement once the optional chain has proved it exists. That is simpler than fighting the event type, and it is safe because the listener only runs when the form exists.

Step 5: Add a custom event with its own detail

A CustomEvent carries a detail payload. By default detail is any, which defeats the point. Give it a type with the generic parameter, and register the event name in the global event map so addEventListener can infer it.

TypeScript
interface CartDetail {
  sku: string;
  quantity: number;
}

declare global {
  interface DocumentEventMap {
    "cart:add": CustomEvent<CartDetail>;
  }
}

document.addEventListener("cart:add", (event) => {
  console.log(event.detail.sku, event.detail.quantity);
});

document.dispatchEvent(
  new CustomEvent<CartDetail>("cart:add", {
    detail: { sku: "A-100", quantity: 2 },
  }),
);

export {};
Text
A-100 2

The export {} makes the file a module, which declare global requires. Without it you get error TS2669, "Augmentations for the global scope can only be directly nested in external modules or ambient module declarations." After the augmentation, a typo in the event name no longer silently falls back to a generic Event, because the name is known. Dispatching is not checked against the map, so keep dispatch and listener in one module, or wrap the dispatch in a small typed function.

Step 6: Type a handler passed to a function

When a function accepts a handler, describe it with a function type, not Function.

TypeScript
type Handler<E extends Event> = (event: E) => void;

function on<K extends keyof HTMLElementEventMap>(
  el: HTMLElement,
  type: K,
  handler: Handler<HTMLElementEventMap[K]>,
): void {
  el.addEventListener(type, handler);
}

const box = document.querySelector<HTMLElement>("#box");
if (box) {
  on(box, "keyup", (event) => console.log(event.key));
}
Text
Enter

The generic K ties the event name to the event type. Pass "keyup" and event is a KeyboardEvent. Pass "click" and it is a MouseEvent. That is the same trick the DOM typings use for addEventListener, scaled down to your own helper.

Common mistakes

The first mistake is annotating a handler with Event and then reading .key or .clientX, which exist only on subtypes. The second is casting event.target to an element type to make an error disappear, which hides the delegation case where a child element or a text node is the target. The third is using any for the event parameter in a separately declared function, which turns off every check on it. The fourth is reading currentTarget after an await, where it is null, or expecting it to carry the element type. The fifth is forgetting that querySelector returns Element | null: use the generic form, querySelector<HTMLInputElement>("input"), or an instanceof check, before you read .value.

When the inline form is enough

For a one-off handler, write the arrow function inline in addEventListener and let the map infer the type. Extract and annotate it only when you reuse it or need to remove the listener later, since removeEventListener needs the same function reference.

A practical checklist

When a handler fails to compile, work through the same short list. First, find out which event name the listener is attached to, because that name decides the event interface. Second, ask whether the code needs the element that was clicked or the element that owns the listener, since they are different values with different typing stories. Third, check whether the code runs after an await, where browser-managed fields like currentTarget are no longer reliable. Fourth, prefer a typed variable from the closure over a cast. In our experience these four questions resolve nearly every event typing error we meet, and none of them needs any.

Also inBrowser
Share

Keep reading

Flat illustration of a browser and a server trading a request and a response, with the Google Chrome, Swagger, Postman and NGINX logos.
Browser

The DOM Tree: Nodes, Elements and Text

Understand the DOM tree: node types, the difference between nodes and elements, text and comment nodes, tree navigation properties and how whitespace shows up.

6 min read
Flat illustration of an editor window full of code, with the TypeScript, npm and Node.js logos.
TypeScript

Type Inference in TypeScript

TypeScript works out most types for you. Learn how inference treats let and const, arrays, return values and callbacks, and when to write a type yourself.

7 min read
Flat illustration of an editor window full of code, with the Google Chrome, JavaScript and npm logos.
Browser

script Tags: async, defer and type=module

Compare classic, async, defer and module script tags: when each downloads, when each runs, how order is kept and which one to pick for each kind of script.

6 min read

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.