TypeScript for Real Projects · 26 min · 150 XP
Generics without the headache
Use generics to preserve relationships between inputs and outputs, adding constraints only for operations the implementation needs.
A generic type parameter is a placeholder chosen by the caller. It is useful when types are related: first<T>(items: T[]): T | undefined says the result is the same element type as the array. Replacing T with any loses that relationship; writing separate string and number versions duplicates the function.
function first<T>(items: T[]): T | undefined {
return items[0];
}
const name = first(["Ada", "Lin"]); // string | undefined
const score = first([8, 13]); // number | undefinedInside a generic function, TypeScript lets you use only members known to exist on every possible T. Add a constraint when the algorithm genuinely needs a capability: T extends { id: string } lets you read item.id while preserving every other field on the original item.
function byId<T extends { id: string }>(items: readonly T[]): Map<string, T> {
return new Map(items.map((item) => [item.id, item]));
}
const users = byId([{ id: "u1", name: "Ada" }]);
users.get("u1")?.name; // extra fields survive; missing keys are explicitA generic should express a relationship. If a type parameter appears only once, a normal concrete type or unknown is often clearer. Start with the simplest signature and introduce T when callers need information preserved.
Loading your workspace…