nasheomirro / react-polymorphed

A set of types to help easily create fast polymorphic components.
MIT License
24 stars 3 forks source link

Event handlers do not infer props correctly #2

Closed nasheomirro closed 1 year ago

nasheomirro commented 1 year ago

Components have the correct types but are inferring incorrectly:

const Button = polyRef<"button">(
  ({ as: As = "button", ...props }) => {
    return <As {...props} />;
  }
);

// `event` is of type `any` when it should be of type `React.MouseEvent<HTMLButtonElement, MouseEvent>`
<Button onClick={event => {}} />

Note that onClick still has the correct type, it's just that typescript isn't inferring our function. What's weirder is that if you provide an as prop, or explicitly provide a value for the component type, then it will infer correctly.

// both `event`s have the correct type
<Button<"button"> onClick={event => {}} />;
<Button as="button" onClick={event => {}} />;

Helpful links: https://github.com/kripod/react-polymorphic-types/issues/5 https://github.com/microsoft/TypeScript/issues/44596

nasheomirro commented 1 year ago

Looks like this issue is related to how typescript does inference, see accepted answer. I am not sure if there is a solution at the moment.

nasheomirro commented 1 year ago

After some time the trick with commit 03bf3db is now un-needed, I don't know what changed but it has to be some update to typescript or maybe ts-server (idk).