Hello! Welcome to another lesson in our module on Advanced Component and TypeScript Patterns.
In our last session, we saw how to use React.forwardRef to give parent components controlled, imperative access to a child's underlying DOM node. This made our components more controllable. Today, we're going to tackle another crucial aspect of component design: making them more reusable and flexible.
Our goal for this lesson is to learn how to create generic components in TypeScript that can work with a variety of data types. Imagine building a <List> component. You wouldn't want to create a <UserList>, a <ProductList>, and a <BookList>. You'd want a single, intelligent <List> component that can handle users, products, books, or any other data you throw at it, all while maintaining complete type safety. This is where TypeScript generics come in.
The Challenge of Reusability
Let's start with a practical scenario. A developer wants to build an online shop and needs several <select> dropdown menus on a page for different categories of goods: books, movies, etc.
Typescript generics for React developers
This article, 'Typescript generics for React developers', introduces this exact problem through a short story. It's an excellent way to see why a non-generic approach quickly becomes unmanageable.
Please read from the beginning of the article down to (but not including) the section 'Strongly typed select - actual solution with typescript generics'. Focus on the problems the developer, Judi, faces with her initial non-generic and union-type-based approaches.
As you've just read, simply creating separate components leads to code duplication, and using a union type (Book | Movie) breaks type safety within the component's logic. TypeScript can't guarantee which type is being handled at any given moment, leading to errors. We need a way to tell our component: "You will work with some type, and I'll tell you what that type is when I use you. But for now, just know that all these props are related to that same type."
What are Generics? A Quick Refresher
Before we fix our React component, let's solidify our understanding of generics as a standalone TypeScript concept. Generics are placeholders for types, allowing us to write code that can operate on a variety of types rather than a single one. They are all about defining a relationship between types.
The video below provides a fantastic, ground-up explanation of why generics are needed and how they work in the context of a simple function.
TypeScript Generics are EASY once you know this
To understand generic components, we first need to be crystal clear on generic functions. Watch this video 'TypeScript Generics are EASY once you know this' by ByteGrad to see a clear breakdown of the concept.
Watch the first four minutes of the video (00:00 - 04:08). Pay close attention to how the instructor moves from using any (unsafe) to a specific type (not reusable), and finally to a generic type parameter <T> to create a function that is both safe and reusable.
The key insight from the video is that the type parameter T allows us to codify a relationship—in this case, that the type of the function's output array depends directly on the type of its input.
Building a Generic React Component
Now, let's apply this powerful concept to our React component. We will make our component's props generic, connecting the type of the data we pass in (values) to the type of the data we get out (onChange).
The Generic Syntax
For a functional component in a .tsx file, the syntax for introducing a generic type parameter looks like this:
// The `<T,>` with a trailing comma is important in .tsx files
// to distinguish it from a JSX tag.
const MyGenericComponent = <T,>(props: MyGenericComponentProps<T>) => {
// ... component logic
};
And the props type would also be generic:
interface MyGenericComponentProps<T> {
items: T[];
onItemSelect: (item: T) => void;
}
Notice how T is used in both items and onItemSelect. This is the relationship! TypeScript now knows that if you pass an array of User objects, the onItemSelect function must accept a User object.
Constraining the Generic Type
There's one more piece to the puzzle. In our <Select> component example, we need to render each item, which means we need to access properties like item.id (for the key) and item.title (for the label). But if T can be any type, how can we be sure it has an id or a title?
We can't. This is where generic constraints come in, using the extends keyword. We can tell TypeScript: "T can be any type, as long as it has the properties I need."
type BaseItem = {
id: string | number;
title: string;
};
// Here, we constrain T to be a type that is compatible with BaseItem.
const MyGenericComponent = <T extends BaseItem>(props: MyGenericComponentProps<T>) => {
// ... now we can safely access props.items[0].id
};
Let's see how this all comes together to solve Judi's problem.
Typescript generics for React developers
Now, let's return to the 'Typescript generics for React developers' article and see the final, working solution.
Please read the section 'Strongly typed select - actual solution with typescript generics'. This will walk you through the complete, final code, explaining the <TValue extends Base> syntax and showing how it provides perfect type safety when the component is used.
A More Powerful Pattern: Generic Lists with Render Props
The generic <Select> is a great example. A more general and widely used pattern is a generic list or table component that accepts a renderItem function as a prop. This decouples the generic container logic (handling the list) from the presentation logic (how each item looks).
Let's look at how to build a GenericList component.
import React from 'react';
// 1. Define the constraint: any item in our list must have an ID.
interface ListItem {
id: number | string;
}
// 2. Define the generic props interface.
// It uses T for the items array, the selection handler, and the render function.
interface GenericListProps<T extends ListItem> {
items: T[];
onItemSelect: (item: T) => void;
// The renderItem function receives a typed item and returns a JSX element.
renderItem: (item: T) => React.ReactNode;
}
// 3. Define the generic component.
// Note the <T extends ListItem> constraint.
export function GenericList<T extends ListItem>({
items,
onItemSelect,
renderItem,
}: GenericListProps<T>) {
return (
<ul>
{items.map((item) => (
// 4. We can safely access item.id because of the constraint.
<li key={item.id} onClick={() => onItemSelect(item)}>
{/* 5. We call the render prop to render the item's content. */}
{renderItem(item)}
</li>
))}
</ul>
);
}
How to use it:
Let's say you have these types and data:
interface User {
id: number;
name: string;
email: string;
}
interface Product {
id: string;
title: string;
price: number;
}
const users: User[] = [
{ id: 1, name: 'Alice', email: 'alice@example.com' },
];
const products: Product[] = [
{ id: 'prod-123', title: 'Gaming Mouse', price: 59.99 },
];
You can now use the same GenericList component for both, with full type safety:
// Using it for Users
<GenericList
items={users}
onItemSelect={(user) => console.log(user.name)} // `user` is correctly typed as User
renderItem={(user) => (
<div>
<strong>{user.name}</strong> ({user.email})
</div>
)}
/>
// Using it for Products
<GenericList
items={products}
onItemSelect={(product) => console.log(product.title)} // `product` is correctly typed as Product
renderItem={(product) => (
<span>
{product.title} - ${product.price}
</span>
)}
/>
TypeScript's inference is smart enough to figure out T from the items prop, so you often don't even need to specify <User> or <Product> when using the component.
Test your understanding!
Your task is to define the types for a generic <DataTable> component. This component should be able to render a table for any kind of data array.
The component will take two props:
data: An array of items of a generic typeT.columns: An array of column definitions. Each column definition should specify aheader(string) and aaccessor(which should be a key of the objectT).
Define the following TypeScript types/interfaces:
ColumnDefinition<T>DataTableProps<T>
How would you constrain T to ensure it's an object type?
Show answer
Here's a possible solution:
// To ensure T is an object, we can constrain it to `object`.
// A more specific constraint might be `T extends { id: string | number }` if an ID is needed for keys.
// The ColumnDefinition is generic over T.
// `accessor` uses the `keyof` operator to ensure it's a valid key of T.
interface ColumnDefinition<T extends object> {
header: string;
accessor: keyof T;
}
// The DataTableProps is also generic over T and uses the ColumnDefinition.
interface DataTableProps<T extends object> {
data: T[];
columns: ColumnDefinition<T>[];
}
// The component signature would then look like this:
function DataTable<T extends object>({ data, columns }: DataTableProps<T>) {
// ... table rendering logic
return (
<table>
<thead>
<tr>
{columns.map(col => <th key={String(col.accessor)}>{col.header}</th>)}
</tr>
</thead>
<tbody>
{data.map((row, index) => (
<tr key={index}>
{columns.map(col => (
// We can safely access row[col.accessor]
<td key={String(col.accessor)}>{String(row[col.accessor])}</td>
))}
</tr>
))}
</tbody>
</table>
);
}
This demonstrates how generics and other TypeScript features like keyof can be combined to create highly flexible and type-safe component APIs.
Conclusion
You've now learned one of the most powerful patterns for creating truly reusable and scalable components in a React and TypeScript codebase.
Key Takeaways:
- Generics for Reusability: Generics allow us to write components that work with multiple data types without sacrificing type safety or resorting to code duplication.
- Codifying Relationships: The core purpose of a generic type parameter (
<T>) is to create a typed relationship between a component's props (e.g., ensuring theitemsarray and theonItemSelecthandler operate on the same type). - Generic Constraints: The
extendskeyword is essential for making generics practical in React. It allows us to guarantee that a generic type will have certain properties (like anidfor akeyprop). - Syntax: Remember the
<T,>syntax with the trailing comma for generic functional components in.tsxfiles to avoid JSX parsing ambiguity.
Preview of the Next Lesson:
We've made our components flexible in the types of data they can accept. In the next lesson, we'll dive even deeper into typing by learning how to utilize TypeScript utility types like Pick, Omit, and ComponentProps. These utilities will give us fine-grained control over our prop interfaces, allowing us to build on existing types, create variations, and interface seamlessly with the props of native HTML elements.