Skip to content

Lesson 4 of 9 · 25m

Generic Components Without Type Gymnastics

Build tables, selects, and lists that preserve item types through render props and callbacks — without drowning callers in type parameters.

The moment you build your second table component, you face the reusable-component problem: the component does not know what a row is, but it must not erase that knowledge for the caller. This is what generics are for — preserving types through a boundary, not showing off.

A generic list that keeps the item type

type SelectListProps<T> = {
  items: T[];
  getKey: (item: T) => React.Key;
  getLabel: (item: T) => string;
  onSelect: (item: T) => void;
};
function SelectList<T>({ items, getKey, getLabel, onSelect }: SelectListProps<T>) {
  return (
    <ul>
      {items.map((item) => (
        <li key={getKey(item)}>
          <button type="button" onClick={() => onSelect(item)}>
            {getLabel(item)}
          </button>
        </li>
      ))}
    </ul>
  );
}

Callers rarely write <T> themselves. TypeScript infers it from items:

<SelectList
  items={users}
  getKey={(user) => user.id}
  getLabel={(user) => user.displayName}
  onSelect={(user) => openUser(user.id)} // user is User, not unknown
/>

That inference is the ergonomics test. If callers must manually specify type parameters for normal usage, the API is probably arranged wrong.

Constrain generics only as much as needed

function keyedById<T extends { id: string }>(items: T[]) {
  return new Map(items.map((item) => [item.id, item]));
}

A constraint says, "I need this much structure." It does not say, "this must be exactly one entity type." Prefer structural constraints like { id: string } over domain-specific base types unless the domain relationship is real.

Render props and children as functions

type Column<T> = {
  header: string;
  cell: (row: T) => React.ReactNode;
};

A typed render callback keeps ownership in the right place: the table knows layout, the caller knows what a row means. Avoid any in the middle — once a row becomes any, every callback downstream becomes guesswork.

Common failure modes

  • items: any[] destroys inference at the entry point.
  • onSelect: (item: unknown) => void forces every caller to cast.
  • Overly clever conditional types make editor autocomplete worse and rarely pay rent in application components.

Field notes

  • Start with one concrete use case, then extract the generic version when the second use case arrives.
  • Prefer several small props (getKey, getLabel) over forcing data into a rigid display shape.
  • If inference fails, inspect the first argument that introduces the generic type; the error is usually there.
  • Export the props type with the component; consumers need it for wrappers and tests.

Was this lesson helpful?

Sign in to rate