← Back to React, page 5

react-0083 · Hard senior

How do you write generic React components in TypeScript (a typed List, a table with keyof columns), and what do constraints buy you?

Declare a type parameter on the component function: function List<T>(props: ListProps<T>). TypeScript infers T from the props, so renderItem and getKey receive the right item type. Add constraints with extends (T extends { id: number }) when the component needs certain fields, and keyof T to tie a prop such as a column name to the data type. This gives compile-time checks without casts or any.

Full answer

A generic component works with many data shapes while keeping each use fully typed. A list that renders any array is the classic example.

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

At the call site TypeScript infers T from items, so in renderItem the parameter is the actual item type. No annotation is needed, and passing the wrong callback is an error.

Constraints. T extends { id: number } tells TypeScript that the component may read id, and rejects data without it. keyof T gives the union of property names of T. A prop sortBy: keyof T accepts only real columns, and row[sortBy] is typed correctly. For columns of a specific kind, use a mapped type to filter keys by value type.

Other patterns. Default type parameters (<T = string>) help optional generics. Inference problems appear when T can be inferred from two places, so make one the source and use NoInfer<T> for the other when needed (TypeScript 5.4 and later). Generic hooks work the same way: function useToggleList<T>(initial: T[]).

Arrow function components in .tsx files need a trailing comma or an extends in the generic, <T,>(props: Props<T>) => ..., because <T> is parsed as JSX. Function declarations avoid that.

React.memo and forwardRef erase generics: the wrapped result has the type parameter replaced by unknown. Cast the result to the generic function type if needed, or avoid wrapping. With React 19, passing ref as a prop removes the forwardRef issue.

Avoid over-engineering: do not make a component generic if one concrete type is enough, and do not use generics only to avoid writing a type.

The example has a generic List and a SortedTable.

tsx
import { useState, type ReactNode } from 'react';

type ListProps<T> = {
  items: readonly T[];
  getKey: (item: T) => string | number;
  renderItem: (item: T) => ReactNode;
};

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

type TableProps<T extends { id: number }> = {
  rows: T[];
  columns: (keyof T)[];
  initialSort: keyof T;
};

function SortedTable<T extends { id: number }>({ rows, columns, initialSort }: TableProps<T>) {
  const [sortBy, setSortBy] = useState<keyof T>(initialSort);
  const sorted = [...rows].sort((a, b) => String(a[sortBy]).localeCompare(String(b[sortBy]), undefined, { numeric: true }));

  return (
    <table>
      <thead>
        <tr>
          {columns.map((column) => (
            <th key={String(column)}>
              <button onClick={() => setSortBy(column)}>{String(column)}</button>
            </th>
          ))}
        </tr>
      </thead>
      <tbody>
        {sorted.map((row) => (
          <tr key={row.id}>
            {columns.map((column) => (
              <td key={String(column)}>{String(row[column])}</td>
            ))}
          </tr>
        ))}
      </tbody>
    </table>
  );
}

type Course = { id: number; title: string; hours: number };
const courses: Course[] = [
  { id: 1, title: 'Science', hours: 12 },
  { id: 2, title: 'Maths', hours: 9 },
];

export default function App() {
  return (
    <div>
      <List items={courses} getKey={(course) => course.id} renderItem={(course) => course.title.toUpperCase()} />
      <SortedTable rows={courses} columns={['title', 'hours']} initialSort="title" />
    </div>
  );
}

The file passed the TypeScript compiler in strict mode. Passing a column such as "price" to SortedTable, or rows without an id, is a compile error. The check pressed each header button in turn, so the table ends sorted by hours. Rendered result: <div><ul><li>SCIENCE</li><li>MATHS</li></ul><table><thead><tr><th><button>title</button></th><th><button>hours</button></th></tr></thead><tbody><tr><td>Maths</td><td>9</td></tr><tr><td>Science</td><td>12</td></tr></tbody></table></div>

Key points

  • Put a type parameter on the component function and let TypeScript infer it from props.
  • Use extends constraints for required fields and keyof T for column-like props.
  • Arrow functions in tsx need <T,> or an extends. Function declarations avoid the issue.
  • memo and forwardRef lose generics, so cast or avoid them. React 19 ref props help.
  • Do not add generics when one concrete type is enough.

Common mistakes

  • Using any or type assertions instead of a type parameter.
  • Forgetting the extends constraint and then reading a field that may not exist.
  • Writing generic arrow functions in tsx without the comma and getting a JSX parse error.
  • Wrapping a generic component in memo and losing its type parameter.
  • Making components generic when a single concrete type would do.

Follow-ups

  • How does NoInfer help when inference picks the wrong source?
  • How would you restrict columns to keys whose values are numbers?
  • Why do memo and forwardRef break generic components?

Tips

  • Explain inference at the call site. It is the value of generics.
  • Show one constraint with extends and one with keyof.
  • Mention the arrow function gotcha in tsx. It is practical.