Skip to content
jshacks.dev
TypeScript

How to Type a Generic React Component

Write a generic React component in TypeScript 6 with type parameters and constraints, inferred from props, and keep generics through memo.

7 min read
Summarize in AI
Flat illustration of a controller handing props to a client-side page, with the React, TypeScript, Vite and Vue.js logos.

Some components are about a kind of data, and not about one shape of it. A select box shows options, a table shows rows, a list renders items, and in each case the component should work for users, products and anything else, while still knowing what the callback receives. That is a job for generics. This post shows how to type a generic React component using TypeScript 6.x and React 19: how to declare the type parameter, how inference works at the call site, how to constrain it, and how to keep generics through memo and forwardRef, which erase them by default. The same code works in the native TypeScript 7 compiler. The language feature is explained in the generics chapter of the handbook.

A generic function component

A component is a function, so a generic component is a generic function. Put the type parameter on the function, and use it in the props.

select.tsxTSX
import type { ReactNode } from "react";

interface SelectProps<T> {
  options: T[];
  value: T | null;
  onChange: (value: T) => void;
  getKey: (option: T) => string;
  renderOption: (option: T) => ReactNode;
}

export function Select<T>({
  options,
  value,
  onChange,
  getKey,
  renderOption,
}: SelectProps<T>) {
  return (
    <ul role="listbox">
      {options.map((option) => (
        <li
          key={getKey(option)}
          role="option"
          aria-selected={option === value}
          onClick={() => onChange(option)}
        >
          {renderOption(option)}
        </li>
      ))}
    </ul>
  );
}

The interface SelectProps<T> carries the parameter, and the function repeats it. Every prop that mentions T is tied to the same type, so the compiler can check that the callbacks agree with the data.

Inference at the call site

You rarely write the type argument. The compiler infers T from the props you pass.

use-select.tsxTSX
import { useState } from "react";
import { Select } from "./select.tsx";

interface Country {
  code: string;
  name: string;
}

const countries: Country[] = [
  { code: "NO", name: "Norway" },
  { code: "JP", name: "Japan" },
];

export function CountryPicker() {
  const [selected, setSelected] = useState<Country | null>(null);

  return (
    <Select
      options={countries}
      value={selected}
      onChange={setSelected}
      getKey={(c) => c.code}
      renderOption={(c) => c.name}
    />
  );
}

From options={countries} the compiler infers T as Country, and the callbacks receive c typed as Country with no annotation. A mistake is caught: changing getKey to (c) => c.id fails, because Country has no id property.

Text
use-select.tsx(20,23): error TS2339: Property 'id' does not exist on type 'Country'.

When inference has nothing to work with, for example an empty array literal, give the type argument explicitly: <Select<Country> options={[]} ... />. The syntax with the type argument after the component name is valid in .tsx files.

Constraining the parameter

Sometimes the component needs to rely on a property. A constraint with extends says what any T must have, and the body can use it.

list.tsxTSX
import type { ReactNode } from "react";

interface ListProps<T extends { id: string | number }> {
  items: T[];
  render: (item: T) => ReactNode;
}

export function List<T extends { id: string | number }>({
  items,
  render,
}: ListProps<T>) {
  return (
    <ul>
      {items.map((item) => (
        <li key={item.id}>{render(item)}</li>
      ))}
    </ul>
  );
}

Now List accepts any item type that has an id, and it uses it as the React key without a getKey callback. A type without an id is a compile error at the call. The constraint is written twice, on the interface and on the function. To avoid the repetition, define a named constraint type, such as type WithId = { id: string | number }, and use it in both places.

A table with keys of T

A more demanding case is a table whose columns refer to properties of the row type. The keyof T operator keeps the column definitions honest.

table.tsxTSX
interface Column<T> {
  key: keyof T & string;
  header: string;
}

interface TableProps<T> {
  rows: T[];
  columns: Column<T>[];
}

export function Table<T extends object>({ rows, columns }: TableProps<T>) {
  return (
    <table>
      <thead>
        <tr>
          {columns.map((c) => (
            <th key={c.key}>{c.header}</th>
          ))}
        </tr>
      </thead>
      <tbody>
        {rows.map((row, i) => (
          <tr key={i}>
            {columns.map((c) => (
              <td key={c.key}>{String(row[c.key])}</td>
            ))}
          </tr>
        ))}
      </tbody>
    </table>
  );
}

A column with key: "nmae" is rejected, because it is not a key of the row type. Inference works here because rows fixes T, and then columns is checked against it. The String(row[c.key]) conversion is deliberate. A cell can hold any value, and React cannot render an arbitrary object, so convert it or accept a render function for the cells that need formatting.

Why memo and forwardRef break generics

Wrapping a generic component in React.memo or forwardRef loses the type parameter. Both are declared to take a component with a fixed props type, so the result is a component of Select<unknown>, and the callbacks become unknown.

memo-bad.tsxTSX
import { memo } from "react";
import { Select } from "./select.tsx";

export const MemoSelect = memo(Select);

After this, MemoSelect accepts props where T is unknown, so renderOption={(c) => c.name} fails because c is unknown. The fix is a cast that restores the generic call signature.

memo-good.tsxTSX
import { memo } from "react";
import { Select } from "./select.tsx";

export const MemoSelect = memo(Select) as typeof Select;

The assertion tells the compiler that the memoized component has the same generic signature as the original. It is safe, because memo does not change the props. In React 19, a function component receives ref as an ordinary prop, so you often do not need forwardRef at all, and a generic component can declare ref in its props directly.

with-ref.tsxTSX
import type { Ref } from "react";

interface BoxProps<T> {
  items: T[];
  ref?: Ref<HTMLDivElement>;
}

export function Box<T>({ items, ref }: BoxProps<T>) {
  return <div ref={ref}>{items.length}</div>;
}

That removes the main reason for the cast, which is good, because each cast is a place where the compiler stops checking.

Default type arguments

A type parameter can have a default, used when inference has nothing to work with.

default.tsxTSX
interface TagListProps<T extends string = string> {
  tags: T[];
  onPick: (tag: T) => void;
}

export function TagList<T extends string = string>({ tags, onPick }: TagListProps<T>) {
  return (
    <div>
      {tags.map((tag) => (
        <button key={tag} onClick={() => onPick(tag)}>
          {tag}
        </button>
      ))}
    </div>
  );
}

Called with tags={["a", "b"] as const}, the component infers the literal union "a" | "b", and onPick receives it. Called with a plain string[], T is string. The constraint to string keeps the keys usable as React keys and button labels.

Pitfalls

Do not use React.FC for a generic component. An arrow function assigned to a constant of type React.FC<Props<T>> cannot declare T in the right place, so use a function declaration or write the generics on the arrow function: const Box = <T,>(props: Props<T>) => .... The trailing comma in <T,> is needed in .tsx files, so the parser does not mistake the type parameter for a JSX tag.

Watch for over generic design. A component with three type parameters and conditional props is hard to read, and hard to call. If you find yourself writing a long constraint, ask whether the component should be two simpler ones, or whether a render callback can replace one of the parameters.

Finally, remember that inference needs a place to look. If the only mention of T is in a callback parameter, the compiler cannot infer it from the arguments, and you will get unknown. Make sure at least one prop that holds a value of type T, such as options or items, is passed.

Passing generic components as props

A generic component often appears as a prop of another component, for example a table that accepts a custom cell renderer. The type of such a prop is a function component with its own type parameter, and writing it takes a little care. A prop typed as ComponentType<Props<T>> accepts a component for one specific T, which is usually what you want, since the parent already knows T. A prop that needs to keep its own type parameter has to be a generic function type, written as <U>(props: Props<U>) => ReactNode, which is rare in practice.

The common situation is simpler. A parent is generic over T, it receives a renderRow: (row: T) => ReactNode callback, and it passes T into the child. As long as the same T flows through every prop, the compiler keeps everything consistent, and a mismatch between the data and a callback is reported where you wrote it.

Testing the generic behavior

Types are part of the contract of a generic component, so test them. A short file that is only type checked can assert both the accepted and the rejected calls. Render the component with data and a callback that match, and add a @ts-expect-error comment above a call whose callback reads a property that the row type lacks. When a later change loosens the signature so that the bad call compiles, the directive becomes unused, and tsc reports it.

This also guards against an easy regression: an edit that adds a second type parameter, or a default that widens T to unknown. Both make existing callers compile and silently remove the checking you wrote the generic for. A type test notices at once, and it costs one small file next to the component.

Also inFrameworks
Share

Keep reading

Flat illustration of two options weighed side by side, with the TypeScript, Node.js, npm and JavaScript logos.
TypeScript

Type Annotations vs Type Assertions

A type annotation asks the compiler to check a value, while an assertion tells it to trust you. Learn the difference, the errors and safer alternatives.

6 min read
Flat illustration of an editor window full of code, with the TypeScript, npm and Node.js logos.
TypeScript

Type Inference in TypeScript

TypeScript works out most types for you. Learn how inference treats let and const, arrays, return values and callbacks, and when to write a type yourself.

7 min read

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.