This is my component
interface Props<C extends React.ElementType> {
as?: C;
children: React.ReactNode;
size?: "mini" | "small" | "medium" | "large";
onClick?: (event: React.MouseEvent<HTMLButtonElement, MouseEvent>) => void;
}
type ButtonProps<C extends React.ElementType> = Props<C> &
Omit<React.ComponentPropsWithRef<C>, keyof Props<C>>;
export const Button = <C extends React.ElementType = "button">({
children,
as,
size = "medium",
onClick,
...restProps
}: ButtonProps<C>) => {
const Component = as || "button";
return (
<Component {...restProps} className={`button-${size}`} onClick={onClick}>
{children}
</Component>
);
};
I can use the component like this:
<Button as="a" onClick={(e) => console.log(e)}>Anchor button</a>
The problem is that the type for the click handler says the event is of type React.MouseEvent<HTMLButtonElement, MouseEvent>, but it isn't. It should be HTMLAnchorElement in this case.
How can I provide the correct type? Ideally I'd somehow use C to get the correct HTMLXyzElement
Here's a TypeScript Playground link where you can play around with the code if you want