Generic Event Parameters: React.MouseEvent<HTMLButtonElement>
You'll learn how to use element-specific generic parameters in React event types to get accurate currentTarget and target types in your event handlers.
Why Generic Parameters Matter
When you write React.MouseEvent, TypeScript knows you're handling a mouse event, but it doesn't know which HTML element triggered it. This means event.currentTarget gets typed as the generic EventTarget instead of the specific element type like HTMLButtonElement or HTMLInputElement.
By adding the generic parameter—React.MouseEvent<HTMLButtonElement>—you tell TypeScript exactly which element type the event comes from. Now event.currentTarget is correctly typed as HTMLButtonElement, giving you autocomplete for button-specific properties like disabled or type.
The Pattern in Action
function handleClick(event: React.MouseEvent<HTMLButtonElement>) {
// currentTarget is correctly typed as HTMLButtonElement
console.log(event.currentTarget.disabled);
console.log(event.currentTarget.type); // "submit" | "button" | "reset"
// target remains EventTarget (could be any child element clicked)
// but you can type-guard it if needed
}
function handleDivClick(event: React.MouseEvent<HTMLDivElement>) {
// currentTarget is now HTMLDivElement
console.log(event.currentTarget.style.display);
}
Think of it like a label on a delivery box: React.MouseEvent tells you it's a package, but React.MouseEvent<HTMLButtonElement> tells you it's specifically a package for buttons, so you know exactly what's inside.
When to Use Specific Generics
Use element-specific generics whenever you access currentTarget properties beyond the basic EventTarget API. For buttons, inputs, forms, and other interactive elements, the specific type unlocks element-specific properties and methods.
Key Takeaway: The generic parameter in React.MouseEvent<T> types currentTarget to the specific element, giving you accurate autocomplete and type safety for element-specific properties.