I have a very simple functional component as follows:
import * as React from \'react\';
export interface AuxProps {
children: React.ReactNode
}
con
You can use ReactChildren
and ReactChild
:
import React, { ReactChildren, ReactChild } from 'react';
interface AuxProps {
children: ReactChild | ReactChildren;
}
const Aux = ({ children }: AuxProps) => (<div>{children}</div>);
export default Aux;
As a type that contains children, I'm using:
type ChildrenContainer = Pick<JSX.IntrinsicElements["div"], "children">
This children container type is generic enough to support all the different cases and also aligned with the ReactJS API.
So, for your example it would be something like:
const layout = ({ children }: ChildrenContainer) => (
<Aux>
<div>Toolbar, SideDrawer, Backdrop</div>
<main>
{children}
</main>
<Aux/>
)
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.
From the TypeScript site: https://github.com/Microsoft/TypeScript/issues/6471
The recommended practice is to write the props type as {children?: any}
That worked for me. The child node can be many different things, so explicit typing can miss cases.
There's a longer discussion on the followup issue here: https://github.com/Microsoft/TypeScript/issues/13618, but the any approach still works.
This has always worked for me:
type Props = {
children: JSX.Element;
};
These answers appear to be outdated - React now has a built in type PropsWithChildren<{}>
. It is defined similarly to some of the correct answers on this page:
type PropsWithChildren<P> = P & { children?: ReactNode };