How would you create a reusable, generic React component using TypeScript, such as a list component that works with any data type?
Short answer
TypeScript generics let a component's prop types adapt to whatever specific data type is actually passed in, letting you write one flexible List component that works correctly and safely whether it is displaying a list of strings, numbers, or custom objects, with full type…
Advertisement
AModel answer
TypeScript generics let a component's prop types adapt to whatever specific data type is actually passed in, letting you write one flexible List component that works correctly and safely whether it is displaying a list of strings, numbers, or custom objects, with full type checking still applying.
type ListProps<T> = {
items: T[];
renderItem: (item: T) => React.ReactNode;
};
function List<T>({ items, renderItem }: ListProps<T>) {
return <ul>{items.map((item, i) => <li key={i}>{renderItem(item)}</li>)}</ul>;
}
<List items={[1, 2, 3]} renderItem={(n) => <span>{n}</span>} />;Real-world example
A design system builds a single generic List component that safely works for a list of product objects on one page and a list of plain usernames on another, with TypeScript correctly checking each usage differently based on the actual data type passed in.
Likely follow-ups
- How does TypeScript know what type T actually is in a specific usage of this component?
- When is it worth the extra complexity of making a component generic versus keeping it more specific?
Related topics