Course contentsShow
← TypeScript
Lesson 1528 of 1,79635. TypeScript with Framework Cross-ReferencesFree lesson

Generic Components with Type Parameters

Build reusable components that accept type parameters for lists, forms, and data displays.

Generic Components with Type Parameters

You'll learn: how to build reusable React components that accept type parameters for lists, forms, and data displays, giving you compile-time safety across different data shapes.

The Problem: One-Off Components for Every Data Type

Imagine building a data table component. Without generics, you'd create UserTable, ProductTable, OrderTable—each with nearly identical logic but hardcoded types. Every new data type means duplicating the entire component.

Generic components solve this by accepting type parameters, letting one component work safely with any data shape while preserving full type safety.

Generic List Components

A list component that works with any item type:

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

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

// Usage with different types
<List items={users} renderItem={(user) => user.name} />
<List items={products} renderItem={(product) => product.title} />

The T flows through items and into renderItem, so TypeScript knows exactly what shape each item has.

Generic Form Components

interface FormProps<T> {
  initialValues: T;
  onSubmit: (values: T) => void;
}

function Form<T>({ initialValues, onSubmit }: FormProps<T>) {
  const [values, setValues] = useState<T>(initialValues);
  // Form logic knows the exact shape of values
  return <form onSubmit={() => onSubmit(values)}>...</form>;
}

Generic Data Display Components

interface DataCardProps<T> {
  data: T;
  fields: Array<keyof T>;
}

function DataCard<T>({ data, fields }: DataCardProps<T>) {
  return (
    <div>
      {fields.map((field) => (
        <div key={String(field)}>{String(data[field])}</div>
      ))}
    </div>
  );
}

The keyof T constraint ensures fields only contains valid property names from data.

Key Takeaway: Generic components with type parameters eliminate duplication while maintaining full type safety—write once, use everywhere with different data types, and let TypeScript catch mismatches at compile time.