nasheomirro / react-polymorphed

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

Constraints with required props still required when using <As /> #5

Closed BrandanKing closed 1 year ago

BrandanKing commented 1 year ago

Hi, I am trying to use onlyAs to create a button that can have the following types OnlyAs<'button' | 'a' | typeof Link> where Link is next/link. However, whenever I add this I get the error 'href' is declared here. It appears that it doesn't apply unknown to typeof props

nasheomirro commented 1 year ago

Hey @BrandanKing , I think the bug you're referring to is that the next/link has a required href prop and the constraints haven't been made to handle that, this is actually something I didn't think of so thank you.

A quick fix for now is to cast the As component to React.ElementType:

polyRef<"button", {}, OnlyAs<"button" | "a" | typeof Link>>(({ as: As = "button", ...props }, ref) => {
  const Elem = As as React.ElementType;
  return <Elem ref={ref} {...props} />  
});

I'll eventually fix the bug in the package myself so that you won't need this workaround in the next version, I could do it now but I'm currently figuring out the best way to do so.

nasheomirro commented 1 year ago

On second thought, I might leave this in for a couple reasons:

After digging deeper, I realized it wasn't a bug, its a feature 😆