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:
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
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 but that wouldnt look great.
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