I can't figure out how to make this work in Typescript. I've got a custom React component which should accept only a certain type of React components as children. I thought I could do something like this, but it doesn't work:
interface ChildProps {
firstName?: string;
lastName?: string;
}
interface ParentProps {
children: Child[]
}
const Child = ({firstName, lastName}: ChildProps) => {return <div>child</div>}
const Parent = ({children}:ParentProps) => {
return <div>{children}<div>
}
<Parent>
<Child> {/* should work */}
<Child> {/* should work */}
<Child> {/* should work */}
<div>this should throw error. Right?</div>
</Parent>
What I was hoping was that I could enforce that only Child components are handed to the parent, and I thought it was easy to do, but I'm a bit stumped. I've tried children: Child[], and children: JSX.Element<Child>[], and a few other things.
I found this SO question, but I can't quite make sense out of it: Typescript: how to set type of children in React Component?
I'm sure it's something dumb I'm doing. Any advice is appreciated. Thanks!!