Course contentsShow
← React
Lesson 1083 of 2,39628. Composition: Compound ComponentsFree lesson

Type Safety with Named Children

Using TypeScript to enforce that only valid child components can be used within the parent.

Type Safety with Named Children

What you'll learn: How to use TypeScript to guarantee that your compound component's children are the correct named subcomponents—and nothing else.

The Problem with Loose Children

When you build compound components like <Tabs> with dot notation (<Tabs.Panel>, <Tabs.List>), TypeScript by default accepts any React children. Someone could accidentally pass a <div> or <span> into your <Tabs> component, breaking your intended API. This defeats the purpose of compound components—tight coupling between specific parent and child components.

Enforcing Valid Children

You can make TypeScript enforce that only your named children are valid by explicitly typing the children prop. Instead of accepting React.ReactNode, you specify exactly which components are allowed:

type TabsProps = {
  children: React.ReactElement<typeof TabsList> | React.ReactElement<typeof TabsPanel>[];
};

This tells TypeScript: "Children must be either a TabsList element or an array of TabsPanel elements—nothing else."

Why This Matters

Without type safety, users can misuse your API and only discover the error at runtime. With typed children, they get immediate IDE feedback: red squiggles, autocomplete suggestions, and compiler errors that guide them toward correct usage. It's self-documenting and prevents bugs before they happen.

Think of it like a restaurant menu that only accepts valid orders—you can't order a "cheeseburger pizza" because the system simply won't allow that combination.

Key Takeaway: Use TypeScript's React.ReactElement<typeof ComponentName> to restrict which child components your compound component accepts, catching API misuse at compile time instead of runtime.