title: Typing the click handler when component is generic (polymorphic react component)
body: <p>This is my component</p>
  <pre><code>interface Props&lt;C extends React.ElementType&gt; {
    as?: C;
    children: React.ReactNode;
    size?: &quot;mini&quot; | &quot;small&quot; | &quot;medium&quot; | &quot;large&quot;;
    onClick?: (event: React.MouseEvent&lt;HTMLButtonElement, MouseEvent&gt;) =&gt; void;
  }
  
  type ButtonProps&lt;C extends React.ElementType&gt; = Props&lt;C&gt; &amp;
    Omit&lt;React.ComponentPropsWithRef&lt;C&gt;, keyof Props&lt;C&gt;&gt;;
  
  export const Button = &lt;C extends React.ElementType = &quot;button&quot;&gt;({
    children,
    as,
    size = &quot;medium&quot;,
    onClick,
    ...restProps
  }: ButtonProps&lt;C&gt;) =&gt; {
    const Component = as || &quot;button&quot;;
  
    return (
      &lt;Component {...restProps} className={`button-${size}`} onClick={onClick}&gt;
        {children}
      &lt;/Component&gt;
    );
  };
  </code></pre>
  <p>I can use the component like this:</p>
  <pre><code>&lt;Button as=&quot;a&quot; onClick={(e) =&gt; console.log(e)}&gt;Anchor button&lt;/a&gt;
  </code></pre>
  <p>The problem is that the type for the click handler says the event is of type <code>React.MouseEvent&lt;HTMLButtonElement, MouseEvent&gt;</code>, but it isn't. It should be <code>HTMLAnchorElement</code> in this case.</p>
  <p>How can I provide the correct type? Ideally I'd somehow use <code>C</code> to get the correct <code>HTMLXyzElement</code></p>
  <p>Here's a <a href="https://www.typescriptlang.org/play?#code/JYWwDg9gTgLgBAJQKYEMDGMA0cDecCuAzksgGZwC+cpUEIcARFKhgwNwBQHwAdjElFLokcAAq0whADwBhOEgAe-HgBNCiFjAB0AUQA2SEEj4AVAJ5gkAPlwc4cFIQD8ALjgzO9tAAtgelcw8bsjo2iEYAHIQKkiecITAAF5IrowgvMAMcAA+jIQgKHp6WbkMRirA+CAljHooUADmSOx2cBA8MnrAaADWqQAUSABuxjDBmloAshBESDojfFIAEiaTADIAQvgwMO36hqPY07Pzo1YAlHAAvDZDEMAqnBRcMBYiWzvt4hCSsvJKxjUGlCugMRlMbxsVzEEmkMhsADJWgB5dIwKThbQyOiQHijb6SADqwBg3jIsis2B6SDMEHIBLhVisnA4ikgsDgaHahHgH12PGucD+imUQMxoIOEMsgoYACNtvyGFZ+jhWj4-AFjJhWo5tfYEskZeVKtU9W0Ol1ematDbmDyGRwKG4+V9YRTLjdbF5ufBseB2qNBY4cqV5Z8eC1WswYPgoAL+q17LIcQG+LgbVo7TAGVQ0HVCIQIigjFccAADMP8gC0ABIcAakBQy1R2p1uj1S63LT0KFZE-ZcOr-IFngOhQB6P24s6tc5PFlcng8uBrXg9QUquC7bBDzUCp24LcQNw8qC8BpsTm+YfGcYgzFRGKUD02VX2aOxgVSFBwbzMUilrsvY4LuI5SOOKDMo6LJstA8CLsuLo8AAqsQUAbi+XpwB+cZwAmY5SBUQx9mOSZIfESRIFcZQZFkFSECgsoGCoJGkfY5H8Eo-ZJuOSGsQR5GONRKBZA21HpDwmS-v+1H8DyWRdu2paDJhCEQAYWh6BADQqb23EDhxIr6eBfHGYJhClquPA9ke1HjqJlHibR-GkYZXFsSZCrtC54FEaxc7QUAA" rel="nofollow noreferrer">TypeScript Playground link</a> where you can play around with the code if you want</p>