Inline Event Handlers vs Named Functions
You'll learn how TypeScript handles type inference differently for inline handlers versus explicitly typed separate functions.
When you write an event handler inline, TypeScript automatically infers the event type from the JSX element you're attaching it to. It knows onClick on a <button> expects a MouseEvent, so you don't need to annotate anything:
<button onClick={(e) => {
// TypeScript knows 'e' is React.MouseEvent<HTMLButtonElement>
console.log(e.currentTarget.value);
}}>
Click me
</button>
The magic happens because TypeScript reads the onClick prop's expected signature and flows that type into your arrow function parameter.
Named functions work differently. When you extract a handler into a separate function, TypeScript no longer has that contextual connection. You must explicitly type the parameter:
// Without annotation, 'e' would be 'any'
function handleClick(e: React.MouseEvent<HTMLButtonElement>) {
console.log(e.currentTarget.value);
}
<button onClick={handleClick}>Click me</button>
Think of it like a conversation: inline handlers receive whispered instructions from their parent JSX ("you're handling a button click"), while named functions stand alone and need written documentation ("this takes a button mouse event").
The tradeoff? Inline handlers get automatic typing but clutter your JSX. Named functions require explicit types but improve readability and reusability. For complex logic, the slight typing overhead of named functions is worth the cleaner component structure.
Key Takeaway: Inline handlers benefit from contextual type inference; named handlers require explicit React.MouseEvent<T> (or similar) type annotations because they lack that JSX context.