Sub topic 14
Writing generic components
This chapter assumes you can write function components with typed props, and that you know TypeScript generics, unions, and keyof. You will build a List component whose item type is inferred from its props. Then you will constrain it, extend it, and avoid the common errors.
Why a component needs a type parameter
Suppose you want a list component that renders any array. You have two weak options:
- Type
itemsasunknown[]. ThenrenderItemreceivesunknown, and every caller must cast. - Type
itemsasany[]. Then nothing is checked.
A generic component fixes this. The component declares a type parameter T. TypeScript infers T from the props a caller passes. It then checks every other prop that mentions T against that inference.
import type { ReactNode } from "react";
interface ListProps<T> {
items: T[];
getKey: (item: T) => string | number;
renderItem: (item: T) => ReactNode;
}
export function List<T>({ items, getKey, renderItem }: ListProps<T>) {
return (
<ul>
{items.map((item) => (
<li key={getKey(item)}>{renderItem(item)}</li>
))}
</ul>
);
}The props interface takes the type parameter, and the function declares it with List<T>. The same T appears in items, getKey, and renderItem.
How inference works at the call site
When you write JSX, you rarely supply T yourself.
interface User {
id: number;
name: string;
}
const users: User[] = [
{ id: 1, name: "Ada" },
{ id: 2, name: "Grace" },
];
export function UserList() {
return (
<List
items={users}
getKey={(user) => user.id}
renderItem={(user) => <span>{user.name}</span>}
/>
);
}TypeScript sees items={users} and infers T = User. The callbacks getKey and renderItem then receive user: User with no annotation. If you write user.nam, the compiler reports the error.
You can also pass T explicitly, and this is sometimes needed:
<List<User> items={[]} getKey={(u) => u.id} renderItem={(u) => u.name} />An empty array gives TypeScript nothing to infer from, so T would fall back to unknown. The explicit <User> fixes that.
Generics in .tsx files
In a .tsx file, arrow functions with a type parameter can be misread as JSX:
// Error in .tsx: <T> is parsed as a JSX tag
const Bad = <T>(props: { value: T }) => <div />;You have three ways around this:
- Use a function declaration, as
Listdoes. This is the simplest option. - Add a trailing comma:
<T,>(props: ...) => .... - Add a constraint:
<T extends unknown>(props: ...) => ....
Prefer function declarations for generic components.
Constraining the type parameter
Sometimes the component needs to know something about T. Use extends to require it.
import type { ReactNode } from "react";
interface SelectProps<T extends { id: string | number }> {
options: T[];
value: T["id"] | null;
onChange: (id: T["id"]) => void;
renderOption: (option: T) => ReactNode;
}
export function Select<T extends { id: string | number }>({
options,
value,
onChange,
renderOption,
}: SelectProps<T>) {
return (
<ul role="listbox">
{options.map((option) => (
<li
key={option.id}
role="option"
aria-selected={option.id === value}
onClick={() => onChange(option.id)}
>
{renderOption(option)}
</li>
))}
</ul>
);
}Now Select accepts only objects with an id. Inside the component you can read option.id safely. The indexed access type T["id"] ties value and onChange to the actual id type of the options, so a list with numeric ids rejects a string value.
The constraint appears twice, on the interface and on the function. To avoid repeating it, you can store it in a named type:
type WithId = { id: string | number };Then write SelectProps<T extends WithId> and Select<T extends WithId>.
Constraining to keys of T
A common pattern is a column-driven table, where each column names a property of the row type. Use keyof T so a typo in a column key is a compile error.
interface Column<T> {
key: keyof T & string;
header: string;
}
interface TableProps<T> {
rows: T[];
columns: Column<T>[];
getKey: (row: T) => string | number;
}
export function Table<T>({ rows, columns, getKey }: TableProps<T>) {
return (
<table>
<thead>
<tr>
{columns.map((col) => (
<th key={col.key}>{col.header}</th>
))}
</tr>
</thead>
<tbody>
{rows.map((row) => (
<tr key={getKey(row)}>
{columns.map((col) => (
<td key={col.key}>{String(row[col.key])}</td>
))}
</tr>
))}
</tbody>
</table>
);
}The & string part narrows keyof T to string keys, because keyof T can also be number or symbol. React keys and text need a string here.
There is an inference catch. If you define columns as a separate constant, TypeScript cannot know it belongs to User:
// key is inferred as string, so it is not checked against User
const columns = [{ key: "name", header: "Name" }];Annotate it as Column<User>[], or write the array inline inside the JSX so inference flows from rows.
Combining generics with native props
A generic component can still extend native element props. Use Omit to remove native props that clash with yours.
import type { ComponentPropsWithoutRef, ReactNode } from "react";
type SelectFieldProps<T extends string> = Omit<
ComponentPropsWithoutRef<"select">,
"value" | "onChange"
> & {
options: readonly T[];
value: T;
onChange: (value: T) => void;
renderLabel?: (option: T) => ReactNode;
};
export function SelectField<T extends string>({
options,
value,
onChange,
renderLabel = (option) => option,
...rest
}: SelectFieldProps<T>) {
return (
<select
{...rest}
value={value}
onChange={(e) => onChange(e.target.value as T)}
>
{options.map((option) => (
<option key={option} value={option}>
{renderLabel(option)}
</option>
))}
</select>
);
}The native select has its own value and onChange, with different types. Without Omit, the intersection would make those props impossible to satisfy. The cast e.target.value as T is a trust boundary. The DOM returns a string, and TypeScript cannot prove it is one of your options. Keep the cast in one place, inside the component.
With a literal array, inference gives a union of literals:
const sizes = ["small", "medium", "large"] as const;
<SelectField
options={sizes}
value="small"
onChange={(size) => console.log(size)} // size: "small" | "medium" | "large"
/>;Generic components and forwardRef
forwardRef does not preserve type parameters. Its return type is a fixed component type, so T collapses to unknown or to its constraint. If you need both, you have two choices:
- Cast the result back to a generic call signature.
- Pass the ref through a differently named prop, such as
innerRef.
import { forwardRef, type ForwardedRef, type ReactNode } from "react";
interface BoxProps<T> {
item: T;
render: (item: T) => ReactNode;
}
function BoxInner<T>(
{ item, render }: BoxProps<T>,
ref: ForwardedRef<HTMLDivElement>,
) {
return <div ref={ref}>{render(item)}</div>;
}
export const Box = forwardRef(BoxInner) as <T>(
props: BoxProps<T> & { ref?: React.Ref<HTMLDivElement> },
) => ReturnType<typeof BoxInner>;The cast is a deliberate compromise. It is safe as long as the signature you write matches what BoxInner does.
Common errors
| Symptom | Cause | Fix |
|---|---|---|
| `T` is `unknown` in callbacks | Nothing to infer from, such as an empty array literal | Pass `<List<User> ...>` or type the variable |
| `Property 'id' does not exist on type 'T'` | The component uses a property without a constraint | Add `extends { id: ... }` |
| Syntax error on `<T>(props) =>` in `.tsx` | The parser reads `<T>` as a JSX tag | Use a function declaration or `<T,>` |
| Callback parameter has the wrong type | Two props infer `T` differently | Move the shared source into one prop, or pass `T` explicitly |
| Column key is just `string` | The array was declared outside the JSX without a type | Annotate with `Column<User>[]` |
Design guidance
Add a type parameter only when the types of two or more props must stay linked. A component that takes items: string[] does not need generics. When it does, keep these habits:
- Use one type parameter when you can. Each extra parameter makes inference and error messages harder to read.
- Constrain
Tto the smallest shape the component needs. - Let inference work. Offer explicit
<T>as a fallback, not a requirement. - Keep any unavoidable cast inside the component, so callers see a clean, checked API.
Exercise
A component is declared as function Picker<T>({ options, onPick }: { options: T[]; onPick: (item: T) => void }). A caller writes <Picker options={[]} onPick={(item) => item.name} />. Why does this fail, and what are two ways to fix it?
Show answer
The empty array literal gives TypeScript no candidate for T, so T is inferred as unknown, and item.name is an error because unknown has no name property. Fix it by passing the type explicitly, as in <Picker<User> options={[]} ... />, or by declaring the array as a typed variable such as const options: User[] = [] and passing that. Constraining T extends { name: string } would also make item.name compile, but it still would not tell the component what the items are.
Exercise
Write the signature of a generic Table column type so that key must be the name of a string property of the row type T. Why is & string included?
Show answer
interface Column<T> { key: keyof T & string; header: string }. keyof T can include number and symbol keys. Intersecting with string keeps only string keys, which is what the rendered header and the React key need.