TypeScript: Generics in Everyday Code
For a long time, I treated generics as something for library authors. When I opened a type definition file and saw <T extends keyof U, K = T[keyof T]>, I closed it again and went back to writing components.
That was a mistake. Most of the generics I need in application code are short and solve very ordinary problems: keeping a function’s input and output connected, writing a component that works with any kind of row, or wrapping an API call without losing the response type.
This post covers the patterns I use most often.
The Problem Generics Solve
Here is a small helper that returns the first item of an array:
function first(items: any[]): any {
return items[0];
}
const name = first(['Ana', 'Emir']); // any
name.toFixed(2); // no error, crashes at runtime
Using any makes the function accept everything, but it also throws away what TypeScript knew about the input. The caller passed an array of strings, and gets back something TypeScript knows nothing about.
A generic keeps that connection:
function first<T>(items: T[]): T | undefined {
return items[0];
}
const name = first(['Ana', 'Emir']); // string | undefined
const total = first([10, 20]); // number | undefined
T is a placeholder for “whatever type the caller uses”. TypeScript infers it from the argument, so the caller never writes first<string>(...).
That is the core idea: a generic connects types between inputs and outputs. If a function’s output type does not depend on its input type, it probably does not need a generic.
Constraining What T Can Be
Sometimes the function needs to know something about T. A helper that groups items by an id needs every item to have one:
function byId<T extends { id: string }>(items: T[]): Record<string, T> {
const result: Record<string, T> = {};
for (const item of items) {
result[item.id] = item;
}
return result;
}
type User = { id: string; name: string; email: string };
const users: User[] = [{ id: 'u1', name: 'Ana', email: 'ana@example.com' }];
const lookup = byId(users);
lookup['u1'].email; // still typed as User
The constraint T extends { id: string } says “any type, as long as it has a string id”. The result is still a Record<string, User>, not a Record<string, { id: string }>. The function only needs id, but the caller keeps the full type.
Using keyof for Property Names
A common next step is passing a property name as an argument. A sorting helper is a good example:
function sortBy<T, K extends keyof T>(items: T[], key: K): T[] {
return [...items].sort((a, b) => (a[key] < b[key] ? -1 : a[key] > b[key] ? 1 : 0));
}
sortBy(users, 'name'); // OK
sortBy(users, 'age'); // Error: "age" is not a key of User
K extends keyof T limits key to the actual property names of T. The editor also suggests them as I type, which is a nice bonus.
Generic Components in React
Tables and lists are where generics pay off most in my React code. Without them, a reusable table either accepts any rows or needs a separate component per data type.
type Column<T> = {
header: string;
render: (row: T) => React.ReactNode;
};
type TableProps<T> = {
rows: T[];
columns: Column<T>[];
getKey: (row: T) => string;
};
function Table<T>({ rows, columns, getKey }: TableProps<T>) {
return (
<table>
<thead>
<tr>{columns.map((c) => <th key={c.header}>{c.header}</th>)}</tr>
</thead>
<tbody>
{rows.map((row) => (
<tr key={getKey(row)}>
{columns.map((c) => <td key={c.header}>{c.render(row)}</td>)}
</tr>
))}
</tbody>
</table>
);
}
When I use it, TypeScript infers T from rows, and every render function gets a correctly typed row:
<Table
rows={users}
getKey={(u) => u.id}
columns={[
{ header: 'Name', render: (u) => u.name },
{ header: 'Email', render: (u) => <a href={`mailto:${u.email}`}>{u.email}</a> },
]}
/>
If I mistype u.emial, I get an error in the column definition rather than an empty cell in the browser.
Wrapping API Calls
Another everyday use is a thin wrapper around fetch:
async function getJson<T>(url: string): Promise<T> {
const response = await fetch(url);
if (!response.ok) {
throw new Error(`Request failed: ${response.status}`);
}
return response.json() as Promise<T>;
}
const user = await getJson<User>('/api/users/u1');
This is useful, but it is important to be honest about what it does. The generic does not check anything at runtime. It is a promise to the compiler that the server returns a User. If the server changes, TypeScript will not notice. I will come back to this in a later post about typing API responses safely, where a validation step makes that promise real.
Note also that here the caller must write <User>, because there is nothing in the arguments to infer T from. That is a hint that the type is an assumption rather than something TypeScript can prove.
Default Type Parameters
Generics can have defaults, just like function parameters:
type ApiResult<T, E = string> =
| { ok: true; data: T }
| { ok: false; error: E };
const a: ApiResult<User> = { ok: false, error: 'Not found' };
const b: ApiResult<User, { code: number }> = { ok: false, error: { code: 404 } };
Most callers use the default, and the few that need a richer error type can provide one.
When Not to Use Generics
Generics are easy to overuse once they click. A few signs that one is unnecessary:
Tappears only once. Infunction log<T>(value: T): void, the type parameter connects nothing.value: unknownsays the same thing more clearly.- The caller always has to specify it explicitly and the function does nothing with it. That is often a cast in disguise.
- The signature is harder to read than the body. In application code, a simpler type that is slightly less precise is often the better trade.
Summary
The generics I use every week are small:
<T>to connect an input type to an output type,<T extends ...>when the function needs to know something aboutT,<K extends keyof T>for property names,- generic props for reusable components such as tables and lists.
Once I started thinking of a generic as “the type the caller brings”, the long signatures in library code became much easier to read too. They are the same idea, just applied many times.