Generic Algorithms
A generic algorithm is a function whose implementation does not depend on one element type. You write it once with a type parameter, and the compiler keeps the element type through the result.
Detailed Explanation
The same loop that finds the first matching element works for users, numbers, and DOM nodes. In JavaScript you write that loop and live with any. In TypeScript you write it with T so the match you return is still a User if the list was User[].
function findFirst<T>(items: readonly T[], pred: (item: T) => boolean): T | undefined {
for (const item of items) {
if (pred(item)) return item;
}
return undefined;
}
The algorithm is generic. The predicate is typed against T, so you cannot compare item.email unless T is constrained or narrowed. The return is T | undefined, not unknown. Call-site inference fills T from items.
This is how Array.prototype.map, filter, reduce, and sort are typed in lib.es5.d.ts. You do not re-type those; you write the same pattern for your own helpers: binary search, sliding-window aggregations, graph walks, zip, groupBy. The type parameter is the payload. The algorithm is the index math and the control flow.
Constraints appear when the algorithm needs a capability. A sort by key needs T[K] to be comparable, so you write K extends keyof T and a comparator on T[K]. A graph walk needs neighbors: T extends { edges: readonly T[] }. Put the minimum capability on the constraint. Do not constrain to a concrete class if an object shape is enough.
Generic algorithms compose with inference. map(findFirst(users, isAdmin), u => u.email) should stay string | undefined without annotations. If you find yourself annotating T at every call, the signature is fighting inference — usually a parameter is in a position the checker cannot read, or you used T only in the return type.
What they cost: a more complicated signature, and error messages that mention T. What they save: a family of copy-pasted helpers that drift, and the as casts that grow around untyped utility functions.
Stay in the type system. The big-O of the loop is a separate question (see time complexity). The generic is about preserving the element type while the loop runs, not about making the loop faster.
Code Examples
1. Search that keeps the element type.
// 1. Search that keeps the element type.
type User = { id: string; email: string };
function findFirst<T>(
items: readonly T[],
pred: (item: T) => boolean,
): T | undefined {
for (const item of items) {
if (pred(item)) return item;
}
return undefined;
}
const users: User[] = [{ id: "u1", email: "ada@example.com" }];
const ada = findFirst(users, (u) => u.id === "u1");
if (ada) console.log(ada.email);2. A constrained algorithm: sort by a key.
// 2. A constrained algorithm: sort by a key.
function sortBy<T, K extends keyof T>(
items: readonly T[],
key: K,
cmp: (a: T[K], b: T[K]) => number,
): T[] {
return [...items].sort((a, b) => cmp(a[key], b[key]));
}
const ordered = sortBy(users, "email", (a, b) => a.localeCompare(b));3. zip: two lists, one pair type.
// 3. zip: two lists, one pair type.
function zip<A, B>(left: readonly A[], right: readonly B[]): [A, B][] {
const n = Math.min(left.length, right.length);
const out: [A, B][] = [];
for (let i = 0; i < n; i++) {
out.push([left[i], right[i]]);
}
return out;
}Common Gotchas
Unconstrained `T` has no fields
`item.email` is a type error until you constrain or pass a predicate that closes over a typed list.
`T` only in the return position will not infer
`function empty<T>(): T[]` needs a default, a contextual type, or an explicit type argument.
Accept `readonly T[]` for inputs you do not mutate
callers with `readonly` arrays can then use the algorithm.
Over-constraining (`T extends User`) makes the helper less reusable
constrain to the members you read.