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
- DOM events:
const handleClick = (e: MouseEvent) => { ... } - React events:
const handleChange = (e: React.ChangeEvent<HTMLInputElement>) => { ... } - Type the handler prop:
onClick?: (e: React.MouseEvent<HTMLButtonElement>) => void; - Access typed properties like
e.currentTarget.valuesafely. - Use
React.SyntheticEventfor generic handlers that work across event types.
Tips
- Prefer
currentTargetovertargetfor type safety becausetargetmay be the specific child that triggered the event. - Define custom event types when working with web components or non-standard events.
Common issues
- Using
anyfor event parameters removes autocomplete and compile-time checks for event properties. - Confusing
MouseEventwithReact.MouseEventcauses type mismatches in React components.