Course contentsShow
← React
Lesson 283 of 2,3968. Props PatternsFree lesson

Type Safety with Render Props in TypeScript

Properly typing render prop functions to ensure type-safe data flow between component and consumer.

Type Safety with Render Props in TypeScript

You'll learn: How to properly type render prop functions so TypeScript catches mistakes in the data you pass and receive.

The Type Safety Challenge

When you use render props, you're passing functions between components. Without proper typing, TypeScript can't verify that the data you're sending matches what the consumer expects. It's like handing someone a mystery box — they don't know what's inside until they open it (and by then, runtime errors happen).

Typing the Render Prop Function

Define the exact shape of the function your component expects as a prop:

interface DataDisplayProps {
  render: (data: { name: string; age: number }) => JSX.Element;
}

function DataDisplay({ render }: DataDisplayProps) {
  const data = { name: "Alice", age: 30 };
  return <div>{render(data)}</div>;
}

// TypeScript now enforces correct usage:
<DataDisplay 
  render={(data) => <p>{data.name} is {data.age}</p>}
/>

Typing the Children as Function Pattern

When using children as a render prop, type it explicitly:

interface ContainerProps {
  children: (count: number) => JSX.Element;
}

function Container({ children }: ContainerProps) {
  return <div>{children(42)}</div>;
}

Now TypeScript knows that children must be a function accepting a number and returning JSX.Element. If you pass the wrong type or forget to call it as a function, you get compile-time errors instead of runtime crashes.

Multiple Arguments

For render props with multiple arguments, tuple types work perfectly:

interface Props {
  render: (name: string, age: number) => JSX.Element;
}

Key Takeaway: Type your render prop functions explicitly to establish a contract between provider and consumer — TypeScript will then catch mismatches before your code runs.