I'm building a component that requires at least two specific child components to be used.
These two components are exported as dot notations from the main component and include defaultProps
to identify them in the main component:
export interface ComponentPropsInterface {
children: React.ReactChild;
}
const Component = ({ children }: ComponentPropsInterface ): JSX.Element => {
const childrenArray = React.Children.toArray(children);
return (
<>
{
// Find a component with the wanted prop and place it in a specific place
childrenArray.filter(
(child) =>
child.props.__TYPE === 'Trigger'
)[0]
}
</>
);
};
const Trigger = ({
children,
}: {
children: React.ReactChild;
__TYPE?: string;
}) => <>{children}</>;
// Prop is assigned here automatically
Trigger.defaultProps = {
__TYPE: 'Trigger',
};
// Export as dot notation
Popover.Trigger = Trigger;
// Export component
export default Component;
In the above I'm checking if Component
has children, which is okay, but it's not failproof.
I would like to ensure children
has a at least one child
with the __TYPE === 'Trigger'
prop.
Is there any way to do this directly from Typescript? Or should I throw an error if the child component I need isn't present?
EDIT: For precision's sake, I'd like the error to appear in the IDE on the parent <Component/>
when it is used without one of the required children.