Is there a way to enforce children of a particular component type?
I'm wanting to make a component that only accepts children that are a specific component so for example:
I tried playing around with
FlowProps
and FlowComponent
but couldn't quite get it to work. I think I'm pretty close but I'm not sure how I can allow passing the result of calling <Code /> while also enforcing the children are of type Code
.
So as a prop, items: (typeof Code)[]
for example allows me pass in Code
but not <Code />
.6 Replies
There isn't really. TypeScript's JSX inference is very limited, and if you plan for runtime checks, it's impossible.
What you could do is, instead of JSX children, you could just accept an array of objects
I was starting to think this wasn't possible in SolidJS, kind of bummed about it but as long as there is a way to enforce using props that would work too
This works as well but I guess its just a matter of preferred ergonomics. I saw Material UI implementation in solid uses children as the API for things like this, I just haven't checked if they do any enforcing of children type (I'm guessing not?) 🤔
Do you mind giving me an example of when one might use
FlowProps
? I thought it was for the case I mentioned.Maybe
https://playground.solidjs.com/anonymous/04756246-2f09-4149-9472-f7811c2842fc cheeky way of filtering out incorrect children.
but no way to give type-errors sadly: https://www.totaltypescript.com/type-safe-children-in-react-and-typescript
Solid Playground
Quickly discover what the solid compiler will generate from your JSX template
Total TypeScript
You Can't Make Children "Type Safe" in React & TypeScript
Learn why it's not possible to restrict the type of children in React components with TypeScript.
You could look at the jsx-tokenizer from solid-primitives. It doesn't exactly do what you're asking, but it might help enforce the pattern https://primitives.solidjs.community/package/jsx-tokenizer
Solid Primitives
A library of high-quality primitives that extend SolidJS reactivity
From their examples: