In below React TypeScript component, TypeScript is complaining at child.type
?
Argument of type 'string | JSXElementConstructor' is not assignable to parameter of type '(({ src, alt }: CardImageProps) => Element) | (({ children }: CardBodyProps) => Element)'. Type 'string' is not assignable to type '(({ src, alt }: CardImageProps) => Element) | (({ children }: CardBodyProps) => Element)'.
How to fix this TypeScript error?
const Card = ({ children }:CardProps) => {
const allowed = [CardImage, CardBody];
return (
<div
{React.Children.map(children, (child) => {
if (!allowed.includes(child.type)) return;
return child;
})}
</div>
);
};
Card.Image = CardImage;
Card.Body = CardBody;
export default Card;
The error you're facing is because of the signature of the
Array.prototype.includes
method. Given that yourallowed
array is of typeJSXElementConstructor[]
andchild.type
is astring | JSXElementConstructor
, you cannot compare astring
and aJSXElementConstructor
.There's some issues with your approach however:
child
might beundefined
ornull
and you're directly accessingchild.type
.child.type
might be a string (for in-built HTML tags) or a function for custom components, or evenundefined
for simple text.How about filtering your
children
like this?This way you make sure that your
child
is indeed aReactElement
, it is not a built-in HTML component, and that it is one of either of your allowed components.With this in mind, if you were to render something like:
Only
CardImage
andCardBody
will be rendered.You can check out the following CodeSandbox to help you out: