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

Generic Props for Flexible Components

Create reusable components with generic type parameters to handle multiple data types safely.

Generic Props for Flexible Components

You'll learn how to create reusable React components that accept different data types while maintaining full TypeScript safety.

The Core Idea

Sometimes you need a component that works with various data shapes—a list that displays users or products, a dropdown for strings or numbers. Instead of writing separate components or using any (losing type safety), you can use generic type parameters to let TypeScript infer or explicitly define the types at each usage.

Think of it like a customizable mold: the component's structure stays the same, but you specify what material (type) goes into it each time you use it.

How It Works

Add a type parameter (conventionally <T>) to your component function, then use T in your props interface:

interface ListProps<T> {
  items: T[];
  renderItem: (item: T) => React.ReactNode;
}

function List<T>({ items, renderItem }: ListProps<T>) {
  return (
    <ul>
      {items.map((item, index) => (
        <li key={index}>{renderItem(item)}</li>
      ))}
    </ul>
  );
}

Now use it with different types:

// TypeScript infers T = User
<List 
  items={users} 
  renderItem={(user) => user.name} 
/>

// TypeScript infers T = Product
<List 
  items={products} 
  renderItem={(product) => product.title} 
/>

The renderItem callback automatically knows whether it receives a User or Product based on the items array type. No type assertions needed—full autocomplete and safety!

Key Takeaway: Generic props let you write one component that adapts to multiple data types, preserving TypeScript's type checking and inference at every usage site.