日本語

How to Build Typed List and Select Components with Generics in React

​​React​Generics,TypeScript

When you build list and select components to work with any data, the props types tend to become any or unknown. If you write the component with a generic, such as function List<T>(props: ListProps<T>), the type of the array you pass carries through to renderItem and onChange. You can then use the component with full types without writing a separate component for each kind of data.

In my test environment, I built List and Select with generics, and checked the type-check results, the HTML they output, and how they behave in Chromium.

Note

The test environment is Ubuntu 24.04, Node.js 22.22.0, and Chromium 141. I used react / react-dom 19.3.1, @types/react 19.3.0, and typescript 7.0.2. I type-checked with tsc, checked the HTML with renderToStaticMarkup from react-dom/server, and checked the browser behavior by running code transpiled with esbuild (a development build) in Chromium and operating it with Playwright.

Write a list component with the type parameter T

The following List takes an array items and displays each item with renderItem. T is the type of the data in the list.

tsx
import type { Key, ReactNode, Ref } from 'react';

type ListProps<T> = {
  items: T[];
  getKey: (item: T) => Key;
  renderItem: (item: T) => ReactNode;
  emptyText?: string;
  ref?: Ref<HTMLUListElement>;
};

export function List<T>({ items, getKey, renderItem, emptyText = 'ありません', ref }: ListProps<T>) {
  if (items.length === 0) return <p>{emptyText}</p>;
  return (
    <ul ref={ref}>
      {items.map((item) => (
        <li key={getKey(item)}>{renderItem(item)}</li>
      ))}
    </ul>
  );
}

List does not know what the data contains. So the caller decides what to use for the list key through getKey.

The caller does not need to write T.

tsx
type Cat = { id: number; name: string; age: number };
type Food = { code: string; title: string; price: number };

<List items={cats} getKey={(c) => c.id} renderItem={(c) => `${c.name}(${c.age}歳)`} />
<List items={foods} getKey={(f) => f.code} renderItem={(f) => `${f.title} ${f.price}円`} />

Since the type of cats is Cat[], T is inferred as Cat, and the parameter c in getKey and renderItem is also Cat. This is type argument inference, described in the TypeScript generics documentation. When I ran tsc in the test environment, it reported no errors. The HTML is as follows (I added line breaks before the tags to make it easier to read).

html
<ul>
<li>たま(3歳)</li>
<li>みけ(5歳)</li>
<li>くろ(1歳)</li></ul>
<ul>
<li>カリカリ 800円</li>
<li>ちゅーる 300円</li></ul>

The type of c is Cat, so writing a property that Cat does not have stops at the type check.

tsx
<List items={cats} getKey={(c) => c.id} renderItem={(c) => c.title} />
text
errors/WrongUsage.tsx(11,68): error TS2339: Property 'title' does not exist on type 'Cat'.

In a select component, return the selected value as T too

The following Select lets you choose one item from a <select> and returns the selected data itself through onChange. It uses T for the types of value and onChange as well.

tsx
type SelectProps<T> = {
  label: string;
  options: T[];
  value: T | null;
  onChange: (value: T | null) => void;
  getKey: (option: T) => string;
  getLabel: (option: T) => string;
};

export function Select<T>({ label, options, value, onChange, getKey, getLabel }: SelectProps<T>) {
  return (
    <label>
      {label}
      <select
        value={value === null ? '' : getKey(value)}
        onChange={(e) => {
          const found = options.find((option) => getKey(option) === e.target.value);
          onChange(found ?? null);
        }}
      >
        <option value="">選んでください</option>
        {options.map((option) => (
          <option key={getKey(option)} value={getKey(option)}>
            {getLabel(option)}
          </option>
        ))}
      </select>
    </label>
  );
}

The value of an <option> is a string, so I made getKey return a string. The component finds the data in options that matches the selected string and passes that data to onChange.

The caller can pass the setter from useState directly to onChange.

tsx
const [cat, setCat] = useState<Cat | null>(null);

<Select
  label="猫"
  options={cats}
  value={cat}
  onChange={setCat}
  getKey={(c) => String(c.id)}
  getLabel={(c) => c.name}
/>

When I wrote (c) => c.id for getKey, it returned a number, and I got the type error Type 'number' is not assignable to type 'string'.

T is decided by all the props

T is not decided by options alone. value and onChange also provide clues. I tested passing a function that takes food to the cat Select by mistake.

tsx
const showFood = (food: Food | null) => console.log(food?.title);

<Select label="猫" options={cats} value={cat} onChange={showFood} getKey={(c) => String(c.id)} getLabel={(c) => c.name} />

The mistake was in onChange, but the errors appeared at options, value, getKey, and getLabel (I omit the rest of the error explanations).

text
errors/WrongUsage.tsx(12,25): error TS2322: Type 'Cat[]' is not assignable to type 'Food[]'.
errors/WrongUsage.tsx(12,40): error TS2322: Type 'Cat | null' is not assignable to type 'Food | null'.
errors/WrongUsage.tsx(12,96): error TS2339: Property 'id' does not exist on type 'Food'.
errors/WrongUsage.tsx(12,120): error TS2339: Property 'name' does not exist on type 'Food'.

In this example, T was decided as Food, and the props that do not match Food produced errors. The type check catches the mistake, but the error location may not match where the mistake was made.

If you want to decide T yourself, you can write the type argument in JSX as well, such as <Select<Cat> ...>. Since TypeScript 2.9, you can pass type arguments to JSX elements. When I wrote the same mistake as <Select<Cat> ...>, the error appeared at onChange (I omit the rest of the explanation).

text
errors/ExplicitType.tsx(9,55): error TS2322: Type '(food: Food | null) => void' is not assignable to type '(value: Cat | null) => void'.

Passing an empty array makes T never

If you pass an empty array as is, such as items={[]}, nothing remains to decide T. In my test, T became never, and errors appeared inside getKey and renderItem.

tsx
<List items={[]} getKey={(c) => c.id} renderItem={(c) => c.name} />
text
errors/EmptyArray.tsx(7,41): error TS2339: Property 'id' does not exist on type 'never'.
errors/EmptyArray.tsx(7,66): error TS2339: Property 'name' does not exist on type 'never'.

When I wrote the type argument as <List<Cat> items={[]} ...>, no errors appeared. When I gave the array a type, as in items={[] as Food[]} for a food list, no errors appeared either.

Adding a constraint to T lets you omit getKey

If you can decide that every data item has an id, add the constraint T extends { id: Key } (generic constraints). The component can then use item.id, so getKey is no longer needed.

tsx
type IdListProps<T extends { id: Key }> = {
  items: T[];
  renderItem: (item: T) => ReactNode;
};

export function IdList<T extends { id: Key }>({ items, renderItem }: IdListProps<T>) {
  return (
    <ul>
      {items.map((item) => (
        <li key={item.id}>{renderItem(item)}</li>
      ))}
    </ul>
  );
}

<IdList items={cats} ...> passed the type check. When I passed an array of Food, which has no id, I got a type error (I omit the error reported for renderItem on the same line).

text
errors/Constraint.tsx(23,15): error TS2322: Type 'Food[]' is not assignable to type '{ id: Key; }[]'.
  Property 'id' is missing in type 'Food' but required in type '{ id: Key; }'.

When writing an arrow function, use <T,>

In a .tsx file, if you write <T> on an arrow function, it is read as a JSX tag.

tsx
export const NoComma = <T>(props: { items: T[] }) => <p>{props.items.length}件</p>;

The first error is as follows (I omit the four errors that follow).

text
errors/ArrowGeneric.tsx(1,25): error TS17008: JSX element 'T' has no corresponding closing tag.

When you add a comma as in <T,>, it is read as a type parameter, and no errors appeared. If you write the component with function, this problem does not occur.

For refs, receiving them as props keeps T

In React 19, function components can receive ref as a regular prop. The first List includes ref in its props type, so it can receive a ref while keeping T. When I ran it in Chromium, listRef.current for <List ref={listRef} items={cats} ...> was the UL element, and it had three child elements.

If you wrap the component with forwardRef, as in the style used up to React 18, T is lost.

tsx
const OldList = forwardRef(function OldList<T>(
  { items, renderItem }: OldListProps<T>,
  ref: Ref<HTMLUListElement>,
) {
  return <ul ref={ref}>{items.map((item, i) => <li key={i}>{renderItem(item)}</li>)}</ul>;
});

<OldList items={cats} renderItem={(c) => c.name} />
text
errors/ForwardRef.tsx(17,51): error TS18046: 'c' is of type 'unknown'.

c in renderItem did not become Cat and was unknown instead. The React TypeScript Cheatsheet's "Generic Components with Refs" section also shows how to handle refs manually in generic components. In React 19, receiving the ref as a prop is the simplest approach.

Results of selecting in Chromium

I placed List and Select on one screen and selected a cat and a food.

text
# Initial display: selected cat: none / food: none
# After selecting Mike for the cat: selected cat: Mike (5 years old) / food: none
# After selecting Churu for the food: selected cat: Mike (5 years old) / food: Churu (300 yen)
# After resetting the cat to the placeholder option ("Please choose"): selected cat: none / food: Churu (300 yen)

The same Select returns a Cat for the cat and a Food for the food. I could use the properties of each type directly for display, such as cat.age and food.price. When I reset the selection to the placeholder option, the cat display went back to "none", because null was passed to onChange.

Chromium in the test environment showing a cat list, a food list, and a row reading "no food yet" (the label is in Japanese), with two select boxes below. The screen shows "Mike" selected for the cat and "Churu" selected for the food. Below it reads "Selected cat: Mike (5 years old) / food: Churu (300 yen)" (labels in Japanese)
The screen after selecting Mike for the cat and Churu for the food
Point

Write the props type as ListProps<T> and the component as function List<T>. Leave the processing that depends on the contents of the data (the key and the displayed text) to the caller through functions such as getKey and renderItem.

Use the type parameter T to separate the component from the kind of data

The List and Select written with generics decide T from the array you pass, and that type also applies to the arguments of renderItem and onChange. In my tests, using properties of another type or passing a function that takes a different type stopped at the type check. However, the error location can shift, and an empty array can make T become never. In those cases, write the type argument explicitly, such as <Select<Cat>>.

​Posted by 86