Course contentsShow
← React
Lesson 2344 of 2,39651. TypeScript with React BasicsFree lesson

Typing Optional Children

Handle optional children with ReactNode | undefined and understand when React.PropsWithChildren helps.

Typing Optional Children

What you'll learn: How to properly type components where the children prop might or might not be provided.

Not every component requires children. A <Card> might render just a header and footer, making children optional. TypeScript needs to know when children might be absent so it doesn't complain when you omit them.

The Core Pattern

By default, if you use React.PropsWithChildren<YourProps>, TypeScript assumes children are always present. But if children are truly optional, you need to explicitly type them as ReactNode | undefined:

interface CardProps {
  title: string;
  children?: ReactNode | undefined;
}

function Card({ title, children }: CardProps) {
  return (
    <div className="card">
      <h2>{title}</h2>
      {children}
    </div>
  );
}

// Both valid:
<Card title="Hello" />
<Card title="Hello">Content here</Card>

When PropsWithChildren Doesn't Help

React.PropsWithChildren<T> adds children?: ReactNode automatically, making them optional by default. If you only care about children (no other props), it's convenient. But if you're already defining a full interface, just add children?: ReactNode yourself for clarity—it's the same thing under the hood.

The undefined Clarification

Technically, ReactNode | undefined is redundant (the ? already makes it optional), but some codebases write it explicitly for documentation purposes. Either works; the ? is sufficient.

Key Takeaway: Use children?: ReactNode in your props interface when children are optional—TypeScript will allow the prop to be omitted without errors, and React will handle the undefined case gracefully.