Sub topic 14
Writing generic components
This chapter assumes you can write TypeScript generics (<T>), you know how props and map work in React, and your project compiles TSX in strict mode. You will build a list component that works with any item type while the compiler still checks every prop.
Why a component needs a type parameter
Suppose you write a List component for users and then need the same one for products. Typing items as any[] makes both work, but the compiler stops checking what renderItem receives. Typing it as User[] locks the component to one shape.
A generic component takes a type parameter, just like a generic function. TypeScript infers the parameter from the props you pass, so callers rarely write it by hand.
A generic List
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 type parameter T appears in three places. items fixes what T is. getKey and renderItem must then accept that same T. The component is a plain function, so the <T> goes right after its name.
Using it
import { List } from "./List";
interface Product {
sku: string;
title: string;
price: number;
}
const products: Product[] = [
{ sku: "a1", title: "Lamp", price: 30 },
{ sku: "b2", title: "Desk", price: 120 },
];
export function ProductList() {
return (
<List
items={products}
getKey={(p) => p.sku}
renderItem={(p) => (
<span>
{p.title}: ${p.price}
</span>
)}
/>
);
}TypeScript infers T as Product from items. Inside both callbacks, p is a Product, so p.title autocompletes and p.name is an error. You did not write <Product> anywhere.
Setting T explicitly
Sometimes inference has nothing to work from. An empty array literal gives never[], and the callbacks then see never. In JSX you can pass the type argument directly.
import { List } from "./List";
interface Tag {
id: number;
label: string;
}
export function TagList({ tags }: { tags: Tag[] | undefined }) {
return (
<List<Tag>
items={tags ?? []}
getKey={(t) => t.id}
renderItem={(t) => <b>{t.label}</b>}
/>
);
}The syntax <List<Tag> ...> is valid in .tsx files and fixes T to Tag.
Constraining T
If the component needs something from every item, constrain the parameter with extends. Here every item must have an id, so the getKey prop is no longer needed.
import type { ReactNode } from "react";
interface Identified {
id: string | number;
}
interface SimpleListProps<T extends Identified> {
items: T[];
renderItem: (item: T) => ReactNode;
}
export function SimpleList<T extends Identified>({
items,
renderItem,
}: SimpleListProps<T>) {
return (
<ul>
{items.map((item) => (
<li key={item.id}>{renderItem(item)}</li>
))}
</ul>
);
}Passing items without an id now fails at the call site, with an error that names the missing property.
Common errors
- Generic arrow functions in TSX. Writing
const List = <T>(props: ListProps<T>) => ...in a.tsxfile is parsed as a JSX tag. Use afunctiondeclaration, or write<T,>or<T extends unknown>. - Wrapping with
React.memoorforwardRef. These erase the type parameter, so the result is no longer generic. Cast the result to the generic signature, or avoid the wrapper. - Repeating
Twhere it is not needed. IfTappears only once in the props, it adds nothing. Use a plain type instead.
Exercise
You write export const Select = <T>(props: SelectProps<T>) => <select />; in a .tsx file and the compiler reports a JSX error. What are two ways to fix it?
Show answer
TypeScript parses <T> as the start of a JSX element. Either change it to a function declaration, export function Select<T>(props: SelectProps<T>) { ... }, or keep the arrow function and write the parameter as <T,> or <T extends unknown>.
Exercise
Using List<T> from this chapter, what type does item have in renderItem when you pass items={[1, 2, 3]}?
Show answer
number. TypeScript infers T from items as number, and renderItem and getKey receive that same type.