Course contentsShow
← TypeScript
Lesson 1524 of 1,79635. TypeScript with Framework Cross-ReferencesFree lesson

Event Handler Typing: onClick, onChange, onSubmit

Type event handlers with specific event types like MouseEvent, ChangeEvent, and FormEvent.

Event Handler Typing: onClick, onChange, onSubmit

You'll learn how to type event handlers with specific event types like MouseEvent, ChangeEvent, and FormEvent to catch errors and gain autocomplete for event properties.

Why Event Handler Typing Matters

In React, event handlers receive event objects that contain specific properties and methods. Without proper typing, you lose autocomplete for properties like event.target.value or event.preventDefault(), and TypeScript can't catch mistakes like accessing properties that don't exist.

TypeScript provides specific event types that match each kind of interaction: clicking buttons, changing inputs, submitting forms, and more.

The Core Event Types

React's event system uses synthetic events that wrap browser events. TypeScript provides generic types that take the element type:

  • MouseEvent<T> – for clicks, hovers, mouse movements
  • ChangeEvent<T> – for input value changes
  • FormEvent<T> – for form submissions

The generic parameter T specifies which HTML element triggered the event.

Typing Common Event Handlers

Button Clicks:

const handleClick = (event: React.MouseEvent<HTMLButtonElement>) => {
  console.log(event.currentTarget.disabled);
};

Input Changes:

const handleChange = (event: React.ChangeEvent<HTMLInputElement>) => {
  console.log(event.target.value);
};

Form Submissions:

const handleSubmit = (event: React.FormEvent<HTMLFormElement>) => {
  event.preventDefault();
  // Process form data
};

The Element Type Matters

The generic parameter ensures you only access properties that exist on that element. For example, HTMLInputElement has a value property, but HTMLButtonElement doesn't. TypeScript enforces this distinction.

Key Takeaway: Use MouseEvent<T>, ChangeEvent<T>, and FormEvent<T> with the appropriate HTML element type to get full type safety and autocomplete for event properties in React handlers.