Lesson 39 of 50TypeScript
Generics
Write functions and types that work for any type while keeping full type safety, with constraints, defaults, keyof and library signatures.
Without generics you have two bad choices: write the same function once per type, or type it as any and lose all checking. Generics are the third option, and they are everywhere: Array<T>, Promise<T>, useState<T>, Map<K, V>, every API client. Reading and writing them confidently is a core TypeScript skill, and getProp<T, K extends keyof T> is a classic interview question.
Why generics
Say you want a function that returns the first element of an array.
function firstNumber(items: number[]): number | undefined {
return items[0];
}
function firstString(items: string[]): string | undefined {
return items[0];
}
// ...one per type? No.
function firstAny(items: any[]): any {
return items[0];
}
const x = firstAny(["a", "b"]); // x: any. The type information is gone.A generic function takes a type parameter, conventionally T, written in angle brackets. It is a placeholder that gets filled in at each call.
Press Run (⌘ Enter) to see what happens.Think of T as a parameter for types, just like items is a parameter for values. The relationship "you get back the same type you put in" is now part of the signature.
The signature links input and output through T, but says nothing yet about what T is.
pair?function makePair<A, B>(a: A, b: B): [A, B] {
return [a, b];
}
const pair = makePair("id", 42);Constraints with extends
Inside a generic function, T could be anything, so you can only do things that work on every type. To use a property, constrain T with extends: "T can be any type, as long as it has this shape".
function longest<T>(a: T, b: T): T {
return a.length >= b.length ? a : b;
// Error: Property 'length' does not exist on type 'T'.
}Press Run (⌘ Enter) to see what happens.Now strings and arrays both work (they have length), and the result keeps its exact type. longest(10, 20) is a compile error, because numbers have no length.
Generic types, interfaces and classes
Types can take parameters too. Two you will write constantly:
interface Box<T> {
value: T;
}
type Result<T, E = Error> =
| { ok: true; value: T }
| { ok: false; error: E };
const age: Box<number> = { value: 36 };
const parsed: Result<number, string> = { ok: false, error: "not a number" };
const loaded: Result<string> = { ok: true, value: "hello" }; // E defaults to ErrorE = Error is a default type parameter: if you do not pass one, Error is used. React uses this pattern for useState<T> and useRef<T>.
Classes work the same way:
Press Run (⌘ Enter) to see what happens.history.push(42) would be an error: this stack was created for strings.
keyof with generics
keyof T is the union of a type's property names. Combined with a constraint, it lets you write a property getter that is fully typed.
type User = { id: number; name: string; active: boolean };
type UserKey = keyof User; // "id" | "name" | "active"Press Run (⌘ Enter) to see what happens.Read the signature slowly. K extends keyof T means the key must be one of T's keys. T[K] is an indexed access type: the type of property K on T. So the return type follows the key you pass.
getProp(user, "email");
// Error: Argument of type '"email"' is not assignable to parameter of type '"id" | "name" | "active"'.x?const settings = { theme: "dark", fontSize: 14 };
const x = getProp(settings, "fontSize");Inference tips and when not to use generics
TypeScript infers type parameters from arguments, so you almost never write them at the call site. Pass them explicitly only when there is nothing to infer from, like an empty array or a JSON result.
const ids = new Set<number>(); // nothing to infer from, so say it
const [user, setUser] = useState<User | null>(null);A good rule: a type parameter should appear at least twice, linking two things (an input and an output, or two inputs). If T appears only once, a plain type does the job.
// Pointless generic: T is used once
function log<T>(value: T): void { console.log(value); }
// Same thing, simpler
function log(value: unknown): void { console.log(value); }Generic defaults, and what you get without one
You saw Result<T, E = Error> above. Defaults matter most when a type parameter cannot be inferred. If nothing at the call site tells TypeScript what T is and there is no default, it falls back to the constraint. With no constraint, that is unknown.
declare function readConfig<T>(): T;
const a = readConfig(); // a: unknown
declare function readSettings<T = Record<string, string>>(): T;
const b = readSettings(); // b: Record<string, string>
const c = readSettings<{ port: number }>(); // an explicit type winsFour rules cover almost every case:
- Inference beats the default. If
Tcan be read off an argument, the default is ignored. Defaults only fill gaps. - Defaults go last.
type Pair<T = string, U> = [T, U]fails with "Required type parameters may not follow optional type parameters", for the same reason optional function parameters go last. - A default must satisfy its constraint.
<T extends string = number>is an error: "Type 'number' does not satisfy the constraint 'string'." - A default can refer to an earlier parameter.
<TData = TQueryFnData>says "unless told otherwise, the data has the same type as what the fetcher returns". You will see exactly that in TanStack Query below.
When you choose a default yourself, prefer unknown to any. An unknown default forces the caller to narrow or to pass a type. An any default quietly switches off checking for everyone who forgets, which is how older libraries (and JSON.parse) leak any into a codebase.
Typed helpers: fetchJson<T> and useLocalStorage<T>
The first generic most people write at work is a fetch wrapper. It usually looks like this:
async function fetchJson<T>(url: string): Promise<T> {
const res = await fetch(url);
if (!res.ok) throw new Error(`HTTP ${res.status}`);
return res.json(); // Promise<any>, so this compiles for every T
}
const user = await fetchJson<User>("/api/users/7");It feels typed, but it is a cast with nicer syntax. res.json() returns Promise<any>, and any is assignable to every T, so the compiler is taking your word for it. Notice that T appears only once, in the return type: the "appears at least twice" rule is broken, and that is the giveaway. The day the backend renames name to fullName, this compiles, ships, and renders undefined.
The fix is to make something real produce the T. Pass a parser, and let TypeScript infer T from it:
Press Run (⌘ Enter) to see what happens.Now T appears twice (the parser's return and the function's return), nobody writes <User> at the call site, and a wrong response fails loudly at the boundary. In a real project the parser is a schema, such as Zod's UserSchema.parse, which you met in Type safety in practice.
A React-style storage hook has the same shape and two more traps:
// Reads localStorage[key] with JSON.parse, falls back to initial, writes on change
declare function useLocalStorage<T>(key: string, initial: T): [T, (next: T) => void];
const [theme, setTheme] = useLocalStorage("theme", "dark");
setTheme("blue"); // compiles: T was widened to string
const [mode, setMode] = useLocalStorage<"light" | "dark">("theme", "dark");
setMode("blue");
// Error: Argument of type '"blue"' is not assignable to parameter of type '"dark" | "light"'.First, widening. When the result is a mutable tuple, TypeScript widens the literal "dark" to string, exactly as useState("dark") does. That is one of the few places where passing the type argument explicitly is right: you want the whole union, and inference has only seen one member. Second, the stored value comes back through JSON.parse, which returns any. A value written by last month's version of your app may have a different shape, yet it claims to be T. Library-quality versions take a parse or validate function for exactly this reason.
"T could be instantiated with a different subtype"
This is the generics error people find most confusing. Here is the classic way to hit it:
function withDefaults<T extends { retries: number }>(opts?: T): T {
return opts ?? { retries: 3 };
}
// Error: Type '{ retries: number; }' is not assignable to type 'T'.
// '{ retries: number; }' is assignable to the constraint of type 'T', but 'T' could be
// instantiated with a different subtype of constraint '{ retries: number; }'.Read it from the caller's side. The caller chooses T, not you. Someone can call withDefaults<{ retries: number; url: string }>(), and the signature promises them an object with a url. Your fallback { retries: 3 } has no url. It fits the constraint, but the constraint is only the minimum. T can be anything bigger.
There are three honest fixes, depending on what you meant:
- You did not need a generic. If callers only ever get the options back, type it plainly:
(opts?: RetryOptions): RetryOptions. Most cases end here. - Build the result from the input, so it really contains everything the caller passed:
type Defaults = { retries: number; timeoutMs: number };
const DEFAULTS: Defaults = { retries: 3, timeoutMs: 5000 };
function withDefaults<T extends Partial<Defaults>>(opts: T): Defaults & T {
return { ...DEFAULTS, ...opts };
}
const o = withDefaults({ retries: 5, url: "/api" });
o.url; // string: the caller's extra field survives
o.timeoutMs; // number: filled in by the defaults- Cast with
as T. This silences the error and keeps the lie. Only do it when you can explain in a comment why every possibleTis safe.
The same message appears whenever you return a concrete value where a type parameter is expected, for example returning "x" from function f<T extends string>(): T. The cure is always to ask: "could a caller pick a T that this value does not satisfy?" If yes, the signature is wrong, not the compiler.
Reading library generics
Sooner or later you will hover over a library function and see a wall of type parameters. Here is TanStack Query's useQuery, simplified from its v5 type definitions:
function useQuery<
TQueryFnData = unknown,
TError = DefaultError,
TData = TQueryFnData,
TQueryKey extends QueryKey = QueryKey,
>(
options: UseQueryOptions<TQueryFnData, TError, TData, TQueryKey>,
): UseQueryResult<TData, TError>;Step 1: list the type parameters with their constraints and defaults. Every one has a default, which tells you none is required.
The practical lesson is do not pass type arguments to functions like this. TypeScript has no partial inference: as soon as you write one type argument, every other parameter stops being inferred and takes its default. A tiny version shows the effect:
declare function query<TFn = unknown, TData = TFn>(o: {
fn: () => TFn;
select?: (data: TFn) => TData;
}): TData;
const count = query({ fn: () => [1, 2], select: (d) => d.length }); // number
query<number[]>({ fn: () => [1, 2], select: (d) => d.length });
// Error: Type '(d: number[]) => number' is not assignable to type '(d: number[]) => number[]'.Passing <number[]> set TFn, so TData fell back to its default TFn and select was suddenly wrong. With useQuery, the fix is the same: type the return of queryFn (ideally by validating it) and let everything else flow.
Utility libraries read the same way. @types/lodash declares groupBy roughly as groupBy<T>(collection: List<T> | null | undefined, iteratee?: ValueIteratee<T>): Dictionary<T[]>: one T, inferred from the collection, appearing again in the iteratee and the result. Many library functions also have several overloads. Your editor's hover shows the one that matched, and Go to Definition shows them all, which is the fastest way to answer "why is this any?"
function pickFirst<T extends { id: string }>(items: T[]): T {
return items.length > 0 ? items[0] : { id: "none" };
}f<A = unknown, B = A>(...). You call it as f<string>(...). What happens to B?What does this print?
function wrap<T>(value: T): { value: T; type: string } {
return { value, type: typeof value };
}
const a = wrap(42);
const b = wrap([1, 2]);
console.log(a.type, b.type, b.value.length);Match the syntax to its meaning.
Typed pick
Write a generic pick that copies only the listed keys into a new object.
function pick<T extends object, K extends keyof T>(obj: T, keys: K[]): Pick<T, K>pick({ id: 1, name: "Ada", password: "x" }, ["id", "name"]) → { id: 1, name: "Ada" }If a listed key is not actually on the object (an optional property that is missing), leave it out. Do not change the original.
Generic groupBy
Write a generic groupBy that sorts items into buckets by a key you compute.
function groupBy<T, K extends PropertyKey>(items: T[], getKey: (item: T) => K): Record<K, T[]>groupBy([1, 2, 3, 4, 5], (n) => (n % 2 === 0 ? "even" : "odd"))
// { odd: [1, 3, 5], even: [2, 4] }Items inside each bucket keep their original order. An empty input gives {}.
- generic
- A function, type or class that takes type parameters, so one definition works for many types safely.
- type parameter
- A placeholder for a type, like
Tinfirst<T>, filled in per use (usually by inference). - constraint
T extends Xlimits a type parameter to types that have the shape X.- default type parameter
<E = Error>: the type used when the caller does not specify one.- keyof
- Produces a union of a type's property names, like
"id" | "name". - indexed access type
T[K]: the type of propertyKin typeT.- return-only generic
- A type parameter used only in the return type, like
fetchJson<T>(): Promise<T>. It is a disguised cast. - partial type argument inference
- Inferring some type parameters while you supply others. TypeScript does not do it: pass one and the rest take their defaults.