TypeScript Generics Explained with Examples
On this page
Learning Objective
Write generic functions, types and components that preserve type information through their inputs and outputs, constrain type parameters with extends, use keyof and indexed access with generics, and avoid over-engineering by knowing when a generic adds value.
Concept Explanation
A generic is a type parameter: a placeholder for a type that the caller provides, usually implicitly through inference. Without generics, a function that returns the first element of an array would have to return any, losing all information, or be duplicated for every element type. With a type parameter, function first<T>(items: T[]): T | undefined says "whatever type the elements are, the result has the same type". Calling first on a string array returns string or undefined; on an array of users, it returns User or undefined. The function is written once and remains fully typed for every caller.
Generics are not limited to functions. Types and interfaces take parameters too, as in the RemoteData<T> union from Day 42 or an ApiResponse<T> wrapper. Classes can be generic, such as a typed cache or event emitter. React components can be generic, so a Select<T> component knows that its onChange receives the same type as its options. Most of the time you never write the type argument: TypeScript infers T from the values passed in.
Constraints limit what a type parameter can be. T extends { id: string } means any type that has a string id, which lets the function read item.id safely while still returning the caller's full type, not just the constraint. Combined with keyof, which produces the union of a type's property names, and indexed access types, which look up a property's type with T[K], constraints express powerful relationships. A function getProp<T, K extends keyof T>(obj: T, key: K): T[K] guarantees the key exists and returns precisely the type of that property.
Default type parameters, such as T = unknown, provide a fallback when inference has nothing to go on. Generic types can also be composed: Record<K, V>, Promise<T> and Array<T> are generics from the standard library that you already use. Day 44 builds on this with utility and mapped types, which are generic types that transform other types.
The common mistake is using generics where they add nothing. A type parameter that appears only once, such as function log<T>(x: T): void, provides no relationship and is just a complicated way to write unknown. A useful rule of thumb from the TypeScript team: a type parameter should appear at least twice, linking inputs to outputs or inputs to each other. If it does not, use a concrete type or unknown.
| Pattern | Example | What it guarantees |
|---|---|---|
| Generic function | first<T>(items: T[]): T or undefined | Output matches input element type |
| Generic type | type ApiResponse<T> = { data: T } | Reusable wrappers |
| Constraint | T extends { id: string } | Can read id, keeps the full type |
| keyof with indexed access | get<T, K extends keyof T>(o: T, k: K): T[K] | Key exists, exact property type |
| Default parameter | type Box<T = unknown> | Fallback when not inferred |
| Generic component | Select<T> with options: T[] | onChange receives the same T |
| Unnecessary generic | log<T>(x: T): void | Nothing; use unknown |
Worked Example: A Typed API Helper, groupBy and a Generic Select
The fetch helper carries the response type through, groupBy uses keyof to relate its arguments, and the Select component keeps option and onChange types in sync.
// Response type flows from the call site to the result
async function getJSON<T>(url: string, init?: RequestInit): Promise<T> {
const res = await fetch(url, init);
if (!res.ok) throw new Error(`${url} failed with ${res.status}`);
return res.json() as Promise<T>; // still unchecked at run time: see Day 45
}
interface Product { id: string; category: 'shoes' | 'bags'; price: number }
const products = await getJSON<Product[]>('/api/products');
// K must be a key of T, and the result is keyed by that property's values
function groupBy<T, K extends keyof T>(items: T[], key: K): Map<T[K], T[]> {
const groups = new Map<T[K], T[]>();
for (const item of items) {
const k = item[key];
groups.set(k, [...(groups.get(k) ?? []), item]);
}
return groups;
}
const byCategory = groupBy(products, 'category'); // Map<'shoes' | 'bags', Product[]>
// groupBy(products, 'colour'); // Error: not a key of Product
// Constraint: needs an id, returns the caller's full type
function upsert<T extends { id: string }>(list: T[], item: T): T[] {
const i = list.findIndex((x) => x.id === item.id);
return i === -1 ? [...list, item] : list.with(i, item);
}interface SelectProps<T> {
options: T[];
value: T | null;
getLabel: (option: T) => string;
getKey: (option: T) => string;
onChange: (option: T) => void;
}
function Select<T>({ options, value, getLabel, getKey, onChange }: SelectProps<T>) {
return (
<select
value={value ? getKey(value) : ''}
onChange={(e) => {
const picked = options.find((o) => getKey(o) === e.target.value);
if (picked) onChange(picked);
}}
>
<option value="" disabled>Choose...</option>
{options.map((o) => <option key={getKey(o)} value={getKey(o)}>{getLabel(o)}</option>)}
</select>
);
}
// T is inferred as Product, so onChange receives a Product
<Select options={products} value={null} getKey={(p) => p.id}
getLabel={(p) => `${p.category}: $${p.price}`} onChange={(p) => addToCart(p.id)} />;Each type parameter appears more than once: T in getJSON links the call to the result, K in groupBy links the key to the map's key type, and T in Select links options, value, the callbacks and onChange.
Real-World Examples
- TanStack Query's useQuery and React Hook Form's useForm are generic hooks whose type parameters flow from the query function's return type or the form's default values into every returned value, which is why they provide accurate autocomplete without manual annotations.
- The TypeScript handbook's guidance on writing good generic functions recommends using fewer type parameters, pushing them down to the narrowest usage and ensuring each parameter appears at least twice, warning against generics that relate nothing.
Review Questions & Answers
The generic version preserves the element type, so callers get a precise result type and full checking. The any version discards all type information, so mistakes in how the result is used are never caught.
That K is one of the property names of T. Calls with a key that does not exist on T fail to compile, and T[K] gives the exact type of that property, so the function can return or use it precisely.
The function can safely use id, but the return type is still the caller's full type T, not the reduced constraint. Using { id: string } directly would lose all other properties in the return type.
When the type parameter appears only once, for example only in a single parameter, it relates nothing and behaves like unknown. In that case a concrete type or unknown is simpler and clearer.