Every generic in this guide was compiled under strict TypeScript 7.0.2 and executed, alongside four files written to fail compilation on purpose. The harness is in the typescript-generics example.
TypeScript generics let a function, component, or hook work with multiple types while preserving full type safety. The core syntax is <T>, a type parameter the TypeScript compiler infers from the call site. Use T extends SomeType to add type constraints and control which types are accepted. Generics are the right tool when the output type depends on the input type; use union types when a value can be one of a fixed set. The three most common patterns in React codebases: generic components (typed list or table props), typed custom hooks (useFetch<T> returning the right shape), and API wrappers (fetchApi<User>('/api/users/1') returning ApiResponse<User>). Avoid a generic when the type parameter appears only once, prefer unknown instead. TypeScript 5.4 added NoInfer<T> to control inference direction. TypeScript 5.5 infers type predicates in .filter() callbacks automatically, removing manual (u): u is Type annotations.
Plenty of developers avoid generics or reach for them in the wrong places. (If the language itself is still new to you, the plain-English TypeScript primer comes first.) The patterns below are the ones that turn up in production React codebases. In React code, generics surface most often in three places: custom hooks, API utilities, and component prop types. Generic utility types like Partial<T>, Pick<T, K>, and ReturnType<F> are all built on generics under the hood, so what you learn here also explains how the built-ins behave.
Why TypeScript generics matter
Generics are how you build genuinely reusable components, one function or one React component that handles a string, number, or object type without duplicating the implementation. The syntax uses angle brackets (<T>) to declare a type parameter that the caller fills in at the call site.
Without generics, you're forced to choose between losing type safety (using any) or duplicating code for each type. Per the TypeScript Handbook, generics solve both problems. Which other Handbook chapters earn the same attention? See the map of the TypeScript docs.
The duplication route has a cost that shows up later. Write a first(arr) helper once per entity type and every copy is free to drift from the others: a fix to an edge case lands in one copy and never reaches the rest. One generic first<T> has one body, so a fix lands everywhere at once.
Without generics you're forced to choose between losing type safety with any or duplicating code for each type. You shouldn't have to choose.
// Without generics - loses type information
function firstAny(arr: any[]): any {
return arr[0];
}
const lost = firstAny([1, 2, 3]); // type: any (all type info lost)
// With generics - preserves type information
function first<T>(arr: T[]): T | undefined {
return arr[0];
}
const result = first([1, 2, 3]); // OK: number | undefined
const firstName = first(['Alice', 'Bob']); // OK: string | undefined
Generics, Unions or any: Which Should You Use?
This is the decision people get wrong most often, so the four options side by side:
| Approach | Use when | Type safety | Reusability |
|---|---|---|---|
any | Migrating legacy JS, absolute last resort | None, disables type checking | High but defeats the purpose |
unknown | Value type is unknown at runtime | Forces narrowing before use | Medium |
| Union types | Fixed set of possible types (e.g. 'asc' | 'desc') | High for closed sets | Low, not reusable across types |
| Generics | Output type mirrors input type | Full, TypeScript infers everything | High, one definition covers all types |
Type inference is the process by which TypeScript figures out a generic's concrete type from the arguments passed at the call site, without you writing an explicit <T> annotation. How do you decide which of the four approaches above fits a given function? Work through this order before you write the signature.
- Check whether the set of valid values is fixed and known ahead of time; if so, reach for a union type.
- Check whether the return type mirrors or depends on an input type; if so, that's the textbook case for a generic.
- Check whether the type parameter would appear only once in the whole signature; if so, replace it with
unknownor a concrete type instead. - Only fall back to
anywhen migrating untyped legacy code, and treat it as a temporary marker to remove later.
The rule of thumb for generics: if you know the possible values ahead of time, use a union type. If the caller determines the type and the output mirrors the input, use a generic instead of any or unknown.
Generic components in React
What's the most common React use case for generics? Typed component props:
interface ListProps<T> {
items: T[];
renderItem: (item: T) => React.ReactNode;
keyExtractor: (item: T) => string;
}
function List<T>({ items, renderItem, keyExtractor }: ListProps<T>) {
return (
<ul>
{items.map((item) => (
<li key={keyExtractor(item)}>{renderItem(item)}</li>
))}
</ul>
);
}
// Usage - TypeScript infers T from the items array
<List
items={users}
renderItem={(user) => <span>{user.name}</span>}
keyExtractor={(user) => user.id}
/>
Typing custom hooks with generics
Generic hooks are extremely useful for data fetching, form state, and local storage. When the T you're fetching is an API payload you only have a JSON sample of, the JSON to TypeScript converter turns that sample into the interface you'd otherwise hand-write. Here's a useLocalStorage hook that wouldn't be type-safe without generics:
import { useEffect, useState } from 'react';
function useLocalStorage<T>(key: string, initialValue: T) {
const [storedValue, setStoredValue] = useState<T>(() => {
try {
const item = window.localStorage.getItem(key);
return item ? (JSON.parse(item) as T) : initialValue;
} catch {
return initialValue;
}
});
// Persist after React commits the new value. Computing it from the
// closed-over storedValue instead would drop updates when two calls
// land in the same event (setCount(c => c + 1) twice adds only 1).
useEffect(() => {
window.localStorage.setItem(key, JSON.stringify(storedValue));
}, [key, storedValue]);
// React's setter already accepts a value or an updater (prev: T) => T
return [storedValue, setStoredValue] as const;
}
// Usage
const [theme, setTheme] = useLocalStorage<'light' | 'dark'>('theme', 'light');
React's own hooks are generic in the same way. useActionState<State, Payload> takes two type arguments, and passing only one selects a different overload and fails to compile; the useActionState typing patterns article shows the error that produces and when you can skip the type arguments entirely.
Constraints: limiting a generic type with extends
Type constraints narrow what types a generic will accept. Use extends to set them:
// Only accept objects with an id property
function getById<T extends { id: string }>(items: T[], id: string): T | undefined {
return items.find((item) => item.id === id);
}
// Only accept keys that exist on the object
function pluck<T, K extends keyof T>(obj: T, key: K): T[K] {
return obj[key];
}
const user = { name: 'Alice', age: 30, role: 'admin' };
const name = pluck(user, 'name'); // OK: string
const age = pluck(user, 'age'); // OK: number
// pluck(user, 'email') // ERROR: 'email' not a key
A generic API response wrapper
A common pattern for typed API utilities:
// A union, not { data: T; error: string | null }: the failure branch has no
// data, and the type says so instead of pretending null is a T.
type ApiResponse<T> =
| { data: T; error: null }
| { data: null; error: string };
async function fetchApi<T>(url: string): Promise<ApiResponse<T>> {
try {
const res = await fetch(url);
if (!res.ok) {
throw new Error(`HTTP ${res.status}`);
}
const data = (await res.json()) as T; // unchecked cast: validate at the boundary in real code
return { data, error: null };
} catch (err) {
return { data: null, error: String(err) };
}
}
// Usage
interface User { id: string; name: string; email: string; }
const { data, error } = await fetchApi<User>('/api/users/1');
if (error === null) {
console.log(data.name); // data is narrowed to User here
}
Conditional types
Conditional types let you express type relationships that depend on other types. They follow the pattern T extends U ? X : Y. If T is assignable to U, the result is X, otherwise Y. Three short definitions show the whole mechanism, including infer:
// Named My* so they don't collide with the built-in NonNullable and Awaited
type MyNonNullable<T> = T extends null | undefined ? never : T;
type Flatten<T> = T extends Array<infer U> ? U : T;
type A = Flatten<string[]>; // string
type B = Flatten<number>; // number (not an array, returns as-is)
// Practical example: extract promise return type (the built-in Awaited also unwraps nested promises)
type MyAwaited<T> = T extends Promise<infer U> ? U : T;
type UserData = MyAwaited<ReturnType<typeof fetchUser>>; // the resolved User type
Mapped types and when to use them
Mapped types transform every property of a type. TypeScript ships several built-in generic utility types like Partial, Pick, and Omit, and all of them use mapped types internally:
// How the built-ins are defined (renamed so they don't clash with them)
// Make all properties optional
type MyPartial<T> = { [K in keyof T]?: T[K] };
// Make all properties readonly
type MyReadonly<T> = { readonly [K in keyof T]: T[K] };
// Pick only certain keys
type MyPick<T, K extends keyof T> = { [P in K]: T[P] };
// Practical: form state from an entity type
type FormState<T> = {
[K in keyof T]: {
value: T[K];
error: string | null;
touched: boolean;
};
};
interface LoginForm { email: string; password: string; }
type LoginFormState = FormState<LoginForm>;
// { email: { value: string; error: string | null; touched: boolean }, ... }
Common generic mistakes
Don't overuse generics. If a type parameter appears only once and doesn't connect input to output, you're better off using a concrete type or unknown instead:
// BAD: Unnecessary generic
function log<T>(value: T): void {
console.log(value);
}
// GOOD: Just use unknown (or any if you need it)
function logValue(value: unknown): void {
console.log(value);
}
Do use generics when the return type mirrors the input:
// GOOD: The output type depends on the input type
function identity<T>(value: T): T {
return value;
}
Think of generics as "type variables" - they're regular variables, but for types instead of values.
Generics in TypeScript 5.4, 5.5, and 7
Generic syntax itself hasn't changed across these versions, <T extends SomeType> works the same as always. What did improve is inference and tooling performance.
TypeScript 5.4: NoInfer<T>
A utility type that prevents TypeScript from using a parameter for type inference. It's useful when you want one arg to set the type and another to validate against it:
function createPalette<T extends string>(colors: T[], defaultColor: NoInfer<T>): Record<T, string> {
// defaultColor won't widen the T inference, it must match what colors already determined
const palette = {} as Record<T, string>;
return palette;
}
// T is inferred from colors as 'red' | 'blue'
// defaultColor must be exactly 'red' | 'blue', not a different string
createPalette(['red', 'blue'], 'red'); // OK
createPalette(['red', 'blue'], 'green'); // Error: 'green' not assignable to 'red' | 'blue'
Before NoInfer<T>, you'd need a second generic parameter and a constraint to get the same effect.
Type constraint is the extends clause on a generic parameter that limits which types are legal at the call site, catching a mismatched argument at compile time instead of a runtime crash. According to the TypeScript Handbook's generics chapter, a constraint narrows the parameter to a specific shape, like { length: number }, while still letting the compiler infer the exact type the caller passed. That's the mechanism NoInfer<T> builds on: it stops one particular parameter from contributing to inference while every other constraint still applies normally.
TypeScript 5.5: Inferred Type Predicates
TypeScript 5.5 infers type guard predicates automatically, no more manual value is Type annotations for simple patterns:
const users = [null, { name: 'Alice' }, null, { name: 'Bob' }];
// Before TS 5.5, you needed an explicit type predicate
const filteredOld = users.filter((u): u is { name: string } => u !== null);
// TS 5.5+, TypeScript infers the type predicate automatically
const filtered = users.filter(u => u !== null); // type: { name: string }[]
Your typed filter helpers no longer need manual annotations, which removes a line of boilerplate from most generic utility functions that filter out null.
TypeScript 7 (Corsa): Compilation Speed
TypeScript 7's native Go compiler doesn't touch generic syntax, but it checks deeply nested generics (common in API wrappers and React form libraries) much faster than the JS compiler did. The TypeScript compiler processes the same type inference logic; it's just running as a native binary now, shipped as the standard tsc since the July 2026 GA. Want the full story on the rewrite? Start with the TypeScript 7 overview. If CI type-checks take 30+ seconds on complex generics, the TS 7 migration is worth it.
Related Guides
- TypeScript Utility Types: A Practical Developer Guide - Partial, Pick, Omit, and Record are all built on generics; this guide covers when to use each one
- React Server Actions guide - React 19's Actions pattern benefits from typed generics for
useActionStateanduseOptimistic - React Hook Form - typed form validation using generic
FieldValuesandUseFormReturn<T>patterns - TanStack Query - all
useQueryanduseMutationhooks are fully generic; typed API responses out of the box - TypeScript 7 Migration Guide - move to the native Go
tscfor faster compilation of generic-heavy codebases - TypeScript types for AI - typed interfaces constrain what AI code generators can produce, and generics make those interfaces reusable