polymorphic-react-component icon indicating copy to clipboard operation
polymorphic-react-component copied to clipboard

Q: How to limit the Element Type

Open donferi opened this issue 2 years ago • 3 comments

Is there a way we can limit the element type to for eg: Button and a?

Been trying to use this helper but I want to narrow it down in some scenarios like <Button as="a"> while disallowing <Button as="form> or any other element other than button | a.

Haven't been able to figure out how to do it yet. Any pointers would be greatly appreciated!

donferi avatar Jul 11 '22 19:07 donferi

That's an interesting use case.

@ Misael Burboa (a Discord user) had posted this solution when they needed to do the same:

image

The crux is in the HtmlTagsAllowed type alias.

ohansemmanuel avatar Jul 27 '22 15:07 ohansemmanuel

I still need to test this, but in the latest version of TS, you might be able to do this via instantiation expressions as follows: Typescript playground

ohansemmanuel avatar Jul 28 '22 05:07 ohansemmanuel

I still need to test this, but in the latest version of TS, you might be able to do this via instantiation expressions as follows: Typescript playground

I tried this solution and it comes close, but you end up losing html attributes that aren't shared among all the elements (aka href on an anchor). I've created an example here

The example you posted from Discord does seem to work in an example env, but I can't seem to get it actually limit the as prop locally (may be something else I'm missing, going to keep testing and will report back). Hopefully this helps others experiment with their own use case. Working example

jimmynotjim avatar May 27 '23 00:05 jimmynotjim