How to type event handlers in TypeScript

· Category: TypeScript

Short answer

Use specific event types from the DOM or React definitions, such as MouseEvent, KeyboardEvent, and ChangeEvent, instead of generic Event.

Steps

  1. DOM events: const handleClick = (e: MouseEvent) => { ... }
  2. React events: const handleChange = (e: React.ChangeEvent<HTMLInputElement>) => { ... }
  3. Type the handler prop: onClick?: (e: React.MouseEvent<HTMLButtonElement>) => void;
  4. Access typed properties like e.currentTarget.value safely.
  5. Use React.SyntheticEvent for generic handlers that work across event types.

Tips

  • Prefer currentTarget over target for type safety because target may be the specific child that triggered the event.
  • Define custom event types when working with web components or non-standard events.

Common issues

  • Using any for event parameters removes autocomplete and compile-time checks for event properties.
  • Confusing MouseEvent with React.MouseEvent causes type mismatches in React components.