Intermediate · 9 of 16 · 13 min read
Generics
A type parameter is a relationship between types — what that buys over any, how inference fills it in, and the rule for when a generic is worth writing.
- Generics
A generic is a type with a hole in it. The caller fills the hole, and the compiler remembers what they filled it with — which is the entire difference between a generic and switching the type system off.
The hole
function identity<T>(value: T): T {
return value;
}
const a = identity("hello"); // string
const b = identity(42); // number
const c = identity<boolean>(true); // explicit, rarely needed
console.log(a.toUpperCase(), b.toFixed(1), c);
Compare with the two alternatives, neither of which works:
function withAny(value: any): any { return value; }
function withUnion(value: string | number): string | number { return value; }
const a = withAny("hello");
console.log(a.toFixed(2)); // compiles — a is any, and this crashes
const b = withUnion("hello");
// console.log(b.toUpperCase()); // 'toUpperCase' does not exist on string | number
any forgets. The union remembers too little. The generic carries the caller’s type through.
Inference
The type argument is normally worked out from the arguments, and writing it is the exception:
function firstElement<T>(items: T[]): T | undefined {
return items[0];
}
const a = firstElement(["a", "b"]); // string | undefined
const b = firstElement([1, 2]); // number | undefined
// Explicit, where there is nothing to infer from:
function makeEmpty<T>(): T[] { return []; }
const list = makeEmpty<number>();
list.push(1);
// Explicit, to be deliberately wider than the argument:
const widened = identity<string | null>("x");
console.log(a, b, list, widened);
function identity<T>(value: T): T { return value; }
Inference widens literals the same way a let does, which occasionally surprises:
function first<T>(items: T[]): T | undefined { return items[0]; }
const a = first(["admin", "user"]); // string | undefined
function firstLiteral<T extends string>(items: T[]): T | undefined { return items[0]; }
const b = firstLiteral(["admin", "user"]); // "admin" | "user" | undefined
console.log(a, b);
A constraint is what tells the compiler to keep the literal — which is the main reason
<T extends string> appears on functions that do not otherwise need it.
Several parameters
function pair<T, U>(a: T, b: U): [T, U] {
return [a, b];
}
const p = pair("age", 33); // [string, number]
console.log(p[0].toUpperCase(), p[1].toFixed(0));
// Two arguments tied to each other:
function same<T>(a: T, b: T): boolean { return a === b; }
console.log(same(1, 2));
// same(1, "two"); // the two arguments must agree
pair keeps two independent types. same uses one parameter twice, which is how you say “these
two must be the same type” — a constraint no annotation could express.
The rule of two
// Pointless — T appears once:
function logBad<T>(value: T): void { console.log(value); }
// The same thing, honestly:
function logGood(value: unknown): void { console.log(value); }
// Useful — T ties the argument to the return:
function identity<T>(value: T): T { return value; }
// Useful — T ties two arguments together:
function pair<T>(a: T, b: T): [T, T] { return [a, b]; }
console.log(identity("x").toUpperCase());
logGood(1);
A type parameter appearing in exactly one position relates nothing. It is worse than noise, because it looks like it guarantees something — the reader has to work out that it does not.
T appears in |
Verdict |
|---|---|
| one parameter only | drop it; use unknown |
| a parameter and the return | useful |
| two parameters | useful — they must agree |
| a parameter and a constraint on another | useful |
Generic types, not just functions
interface ApiResponse<T = unknown> {
status: number;
data: T;
}
type Result<T, E = Error> =
| { ok: true; value: T }
| { ok: false; error: E };
type Dictionary<V> = Record<string, V>;
const a: ApiResponse<{ id: number }> = { status: 200, data: { id: 1 } };
const b: ApiResponse = { status: 204, data: null }; // uses the default
const c: Result<number> = { ok: true, value: 1 };
console.log(a.data.id, b.status, c.ok && c.value);
A default type parameter supplies the argument when inference has nothing to work from — which is most of the time for a generic type, since there are no values to infer from.
Where you already use them
const items: Array<string> = []; // Array<T>
const lookup = new Map<string, number>(); // Map<K, V>
const later: Promise<number> = Promise.resolve(1);
const lengths = ["a", "bb"].map((s) => s.length); // map<U>
const found = [1, 2, 3].find((n) => n > 1); // number | undefined
console.log(items, lookup.size, lengths, found);
later.then((n) => console.log(n));
Array.prototype.map is the one to point at in an interview: its signature is
map<U>(fn: (value: T) => U): U[], which is exactly “whatever the callback returns, that is what
the new array holds”.
Generics preserve, they do not inspect
A generic function body knows nothing about T beyond its constraint:
function size<T>(item: T): number {
// return item.length; // Property 'length' does not exist on type 'T'
return 0;
}
function sizeConstrained<T extends { length: number }>(item: T): number {
return item.length; // now the body knows
}
console.log(sizeConstrained("hello"), sizeConstrained([1, 2])); // 5 2
That is the division of labour: the caller keeps the precise type, and the body sees only what the constraint promises. Constraints are the next page.
Common mistakes
Reaching for any because a generic looks harder
Mistake. function wrap(value: any): any.
Why it fails. Every call site loses its type, and the error surfaces wherever the result is
used — far from the function.
What to do instead. function wrap<T>(value: T): { value: T }. It is one character more and
keeps everything.
A type parameter that appears once
Mistake. function log<T>(value: T): void.
Why it fails. Nothing is related, so the generic is decoration. Callers gain nothing.
What to do instead. value: unknown, and reserve the parameter for when it relates two
positions.
Writing the type argument at every call
Mistake. identity<string>("x") everywhere.
Why it fails. It is noise — inference already had it — and it goes stale when the argument
changes.
What to do instead. Let it infer, and write the argument only when there is nothing to infer
from or you want something wider.
Check yourself
3 questions from the bank on what you just read. Answering here does not affect your quiz history.
What does function identity<T>(value: T): T preserve that (value: any) => any does not?
A type parameter is usually inferred from the arguments, and the inference keeps the literal where it can.
What is the type of result?
function firstElement<T>(items: T[]): T | undefined {
return items[0];
}
const result = firstElement(["a", "b"]);Why does a generic type parameter usually not need to be written at the call site?
Further reading
Everything above is meant to be enough on its own. These are for when you want the full specification of a detail.
Reaching the end of a lecture marks it as read.