Restricting children to specific component types

I'm wondering if it's possible to define a pair of components, e.g. SpecialTable and SpecialRow, such that the former type only accepts children of the latter type:
<SpecialTable>
<SpecialRow/>
<SpecialRow/>
...
</SpecialTable>
<SpecialTable>
<SpecialRow/>
<SpecialRow/>
...
</SpecialTable>
I assumed that the C in FlowProps<P extends Record<string, any> = {}, C = JSX.Element> was meant for this, but failed attempts and some research seem to indicate otherwise. If the answer is "not possible, and we don't think it should be possible," I'm interested in learning why.
2 Replies
Dakotys
Dakotys4w ago
Afaik TypeScript defaults to JSX.Element for components wrapped in < />. Unfortunately, this is an inherent limitation in how TypeScript handles JSX. https://www.typescriptlang.org/docs/handbook/jsx.html#the-jsx-result-type. So it is not possible to differentiate between <SpecialRow/> and other components like <Some/> or <div>. The best, you could do is enforce
<SpecialTable>
{SpecialRow()}
</SpecialTable>
<SpecialTable>
{SpecialRow()}
</SpecialTable>
but that wouldnt look great.
absent
absentOP4w ago
Thanks --- I didn't realize that it was a limitation of TypeScript itself. And yeah, calling the child component as a function was as close as I got in my attempts. I guess I'll go look at TypeScript internals if I'm still interested in this down the line
Want results from more Discord servers?
Add your server