Course contentsShow
← React
Lesson 1056 of 2,39627. Composition: Render PropsFree lesson

Type Safety with Function Children

Typing function children in TypeScript to ensure consumers receive and use the correct arguments.

Type Safety with Function Children

What you'll learn: How to use TypeScript to enforce correct types when using the function-children pattern, preventing runtime errors and improving developer experience.

Why Type Safety Matters Here

When you use the children-as-function pattern, you're creating a contract: the parent component will call children with specific arguments, and the consuming component expects those arguments to have certain shapes. Without TypeScript, this contract exists only in documentation and memory. With proper typing, it becomes enforced at compile time.

Typing the Component Props

The key is typing the children prop as a function signature that matches what you're actually passing:

interface MouseTrackerProps {
  children: (position: { x: number; y: number }) => React.ReactNode;
}

function MouseTracker({ children }: MouseTrackerProps) {
  const [position, setPosition] = useState({ x: 0, y: 0 });

  // ... mouse tracking logic

  return <div>{children(position)}</div>;
}

Now when someone uses your component, TypeScript knows exactly what arguments the function receives:

<MouseTracker>
  {(pos) => (
    // TypeScript knows 'pos' has x and y properties
    <div>Mouse at {pos.x}, {pos.y}</div>
  )}
</MouseTracker>

The Benefits

If a consumer tries to access pos.z or forgets the function entirely and passes JSX directly, TypeScript will catch it immediately. You get autocomplete for the argument properties and instant feedback on mistakes.

Key Takeaway: Type the children prop as a function signature (args) => React.ReactNode to enforce what arguments your component provides and catch consumer mistakes at compile time, not runtime.