I have a very simple functional component as follows:
import * as React from \'react\';
export interface AuxProps {
children: React.ReactNode
}
con
The function component return type is limited to JSXElement | null
in TypeScript. This is a current type limitation, pure React allows more return types.
Minimal demonstration snippet
You can either use a type assertion or Fragments as workaround:
const Aux = (props: AuxProps) => <>props.children>;
const Aux2 = (props: AuxProps) => props.children as ReactElement;
ReactNode
children: React.ReactNode
might be suboptimal, if the goal is to have strong types for Aux
.
Almost anything can be assigned to current ReactNode
type, which is equivalent to {} | undefined | null
. A safer type for your case could be:
interface AuxProps {
children: ReactElement | ReactElement[]
}
Example:
Given Aux
needs React elements as children
, we accidently added a string
to it. Then above solution would error in contrast to ReactNode - take a look at the linked playgrounds.
Typed children
are also useful for non-JSX props, like a Render Prop callback.