My current component looks like the following:
interface MyComponentProps {
children: HTMLSpanElement
}
...
export default function MyComponent({children}: MyComponentProps){
...
return (
<div>
{children}
</div>
)
}
I want my children to only allow a span, no other element.
Problem is, I get an error underneath {children}
telling me that Type HTMLSpanElement is not assignable to ReactNode
It seems this happens with any HTMLElement, giving the error Type HTMLElement is not assignable to ReactNode
I was curious if there’s a way to properly handle such a scenario, or some other method of wanting to set up an instance where I type check to only pass span elements as the child node of a React element.
2
Answers
_or using
type
instead ofinterface
you can use
React's React.ReactElement
type along with theReact.ReactElementProps
utility type. Here’s an example of how you can restrict thechildren
prop to only acceptspan
elements:Now, when you use
MyComponent
TypeScript will enforce that onlyspan
elements (or components withspan
-compatible props) can be passed as children. If you try to pass any other element or component, TypeScript will raise a type error.like this :