Event Handler Props: Typing Callbacks Passed to Children
What you'll learn: How to properly type callback functions when passing them as props from parent to child components.
The Core Idea
When you pass event handlers down to child components as props, you need to define their type signatures carefully. The goal is to be specific enough that TypeScript catches mistakes, but flexible enough that the child component isn't locked into implementation details it doesn't need to know about.
The key decision: Does the child component need to know the exact event type, or just the data it receives?
Two Approaches
Approach 1: Pass the full event type when the child needs event methods like preventDefault():
interface ButtonProps {
onClick: (e: React.MouseEvent<HTMLButtonElement>) => void;
}
Approach 2: Extract only what matters when the child just needs specific values:
interface SearchProps {
onSearch: (query: string) => void; // Child doesn't need the full ChangeEvent
}
// Parent handles the event extraction:
<SearchInput onSearch={(query) => handleSearch(query)} />
Finding the Balance
The second approach is often cleaner—it decouples the child from DOM details. The parent component extracts e.currentTarget.value and passes just the string. This makes the child more reusable and easier to test.
However, if the child needs to call e.stopPropagation() or access event timing, pass the full event type.
Key Takeaway: Type event handler props based on what the child component actually needs—prefer passing extracted data over raw events when possible, but don't hesitate to pass full event types when event methods are required.