Course contentsShow
← TypeScript
Lesson 170 of 1,7964. Type InferenceFree lesson

Event Handler Context

How event listener parameters receive specific event types based on the element and event name.

Event Handler Context

What you'll learn: How TypeScript automatically knows the correct event type when you add listeners to DOM elements.

The Magic of Event Context

When you attach an event listener to a DOM element in TypeScript, something helpful happens: TypeScript looks at both the element type and the event name to figure out exactly what kind of event object you'll receive. You don't have to tell it — it infers this automatically.

Think of it like a restaurant knowing what utensils to bring based on what you ordered. Order soup? You get a spoon. Order steak? Here's a knife. Similarly, add a 'click' listener to a button? TypeScript knows you're getting a MouseEvent. Add a 'keydown' listener to an input? That's a KeyboardEvent.

How It Works

const button = document.querySelector('button');

button?.addEventListener('click', (event) => {
  // TypeScript infers: event is MouseEvent
  console.log(event.clientX); // MouseEvent property ✓
});

const input = document.querySelector('input');

input?.addEventListener('keydown', (event) => {
  // TypeScript infers: event is KeyboardEvent
  console.log(event.key); // KeyboardEvent property ✓
});

Notice you never wrote event: MouseEvent or event: KeyboardEvent. TypeScript figured that out from context — the element type (button, input) combined with the event name string ('click', 'keydown').

This is contextual typing at work: the callback parameter's type is inferred from where and how it's used.

Key Takeaway: TypeScript infers event handler parameter types by analyzing both the DOM element type and the event name string, giving you accurate autocomplete and type safety without manual annotations.