Generic functions
Overview
Some functions don’t care what type of data they handle: getting the first item of an array, removing duplicates, grouping, caching. You could type them with unknown or any, but then the caller loses the type. Generics let you write the function once and keep the exact types for every caller.
The problem
function first(items: unknown[]): unknown {
return items[0];
}
const n = first([10, 20]);
n.toFixed(2);
// error TS18046: 'n' is of type 'unknown'.Typing it with unknown is safe but useless: the information that this was an array of numbers is lost. Typing it with any throws away checking entirely. And writing firstNumber, firstString, firstUser… doesn’t scale.
Type parameters
function first<T>(items: T[]): T | undefined {
return items[0];
}
const n = first([10, 20]); // number | undefined
const s = first(["a", "b"]); // string | undefined
const u = first(users); // User | undefined<T> declares a type parameter — a variable that holds a type instead of a value. Each call chooses what T is. Because the same T appears in the parameter (T[]) and the return type (T | undefined), TypeScript knows that what comes out matches what went in.
T is just a conventional name. Use descriptive names when it helps: <Item>, <TKey, TValue>.
Inference and explicit type arguments
TypeScript infers type arguments from the values you pass, so you rarely write them. You can specify them:
first<number>([10, 20]);
first<string>([10, 20]);
// error TS2322: Type 'number' is not assignable to type 'string'.Explicit type arguments are useful when there’s nothing to infer from — for example, an empty array, or a function whose type parameter only appears in the return type:
const ids = new Set<string>(); // nothing to infer from yet
const data = await fetchJson<User[]>(url); // (more on this pattern in Validating external data)Generic arrow functions
const last = <T,>(items: readonly T[]): T | undefined => items[items.length - 1];The trailing comma in <T,> is only needed in .tsx files, where <T> alone would look like a JSX tag.
Several type parameters
function zip<A, B>(as: A[], bs: B[]): [A, B][] {
return as.slice(0, bs.length).map((a, i) => [a, bs[i] as B]);
}
zip(["Asha", "Ben"], [29, 34]); // [string, number][]Generic callbacks
Generics are especially powerful with callbacks: the type flows into the callback, and the callback’s return type flows out:
function mapValues<T, R>(items: T[], transform: (item: T) => R): R[] {
return items.map(transform);
}
mapValues(["a", "bb"], (s) => s.length); // number[] — s: string, R inferred as numberThat’s exactly how the built-in Array.prototype.map is typed. Look at a few built-in signatures by hovering — map, filter, reduce, Promise.all, Object.fromEntries — and you’ll see generics everywhere.
Generics vs unknown vs any
| Input | Output | Caller gets | |
|---|---|---|---|
(x: any) => any |
anything | any |
no checking at all |
(x: unknown) => unknown |
anything | unknown |
safe, but must re-check |
<T>(x: T) => T |
anything | the same type | the exact type back |
Generics are the right choice when there’s a relationship between types — between input and output, or between several parameters.
When not to use generics
A type parameter that appears only once isn’t relating anything:
function logValue<T>(value: T): void { // T used once
console.log(value);
}
function logValue(value: unknown): void { // simpler, same effect
console.log(value);
}Rule of thumb: every type parameter should appear at least twice — usually once in the parameters and once in the return type. If you can’t say what a type parameter connects, remove it.
Also avoid generics whose type the caller must always specify by hand, like parse<T>(json: string): T. That’s just a type assertion in disguise: parse<User>(text) checks nothing at run time. Return unknown and validate instead.
Remember: a type parameter is a type-level variable. Declare it in
<…>, use it to connect inputs to outputs, and let TypeScript infer it at each call.
A generic toolbox
Write four generic functions and prove their types with annotated variables: (1) last<T>(items: readonly T[]): T | undefined; (2) groupBy<T>(items: readonly T[], keyOf: (item: T) => string): Record<string, T[]>; (3) uniqueBy<T, K>(items: readonly T[], keyOf: (item: T) => K): T[] that keeps the first item for each key; (4) zip<A, B>(as: readonly A[], bs: readonly B[]): [A, B][] that stops at the shorter array. Use them on the people array: the last person’s name, people grouped by city, people unique by city, and names zipped with ages. Print each result.
type Person = { name: string; age: number; city: string };
const people: Person[] = [
{ name: "Asha", age: 29, city: "Pune" },
{ name: "Ben", age: 34, city: "Leeds" },
{ name: "Chen", age: 41, city: "Pune" },
{ name: "Dee", age: 25, city: "Lagos" },
];
// 1. last
// 2. groupBy
// 3. uniqueBy
// 4. ziptype Person = { name: string; age: number; city: string };
const people: Person[] = [
{ name: "Asha", age: 29, city: "Pune" },
{ name: "Ben", age: 34, city: "Leeds" },
{ name: "Chen", age: 41, city: "Pune" },
{ name: "Dee", age: 25, city: "Lagos" },
];
// 1. last
function last<T>(items: readonly T[]): T | undefined {
return items[items.length - 1];
}
// 2. groupBy
function groupBy<T>(items: readonly T[], keyOf: (item: T) => string): Record<string, T[]> {
const groups: Record<string, T[]> = {};
for (const item of items) {
const key = keyOf(item);
(groups[key] ??= []).push(item);
}
return groups;
}
// 3. uniqueBy
function uniqueBy<T, K>(items: readonly T[], keyOf: (item: T) => K): T[] {
const seen = new Set<K>();
return items.filter((item) => {
const key = keyOf(item);
if (seen.has(key)) return false;
seen.add(key);
return true;
});
}
// 4. zip
function zip<A, B>(as: readonly A[], bs: readonly B[]): [A, B][] {
const length = Math.min(as.length, bs.length);
const pairs: [A, B][] = [];
for (let i = 0; i < length; i++) {
pairs.push([as[i] as A, bs[i] as B]);
}
return pairs;
}
const lastPerson: Person | undefined = last(people);
console.log(lastPerson?.name); // Dee
const byCity: Record<string, Person[]> = groupBy(people, (p) => p.city);
console.log(Object.keys(byCity), byCity["Pune"]?.length); // [ 'Pune', 'Leeds', 'Lagos' ] 2
const onePerCity: Person[] = uniqueBy(people, (p) => p.city);
console.log(onePerCity.map((p) => p.name)); // [ 'Asha', 'Ben', 'Dee' ]
const pairs: [string, number][] = zip(people.map((p) => p.name), [29, 34, 41]);
console.log(pairs); // [ [ 'Asha', 29 ], [ 'Ben', 34 ], [ 'Chen', 41 ] ]Summary
- A type parameter (
<T>) is a placeholder for a type, chosen separately for each call. - TypeScript infers type arguments from the values you pass — you rarely write
first<number>(…). - Use the type parameter in both input and output to connect them; that’s what makes a function generic rather than
unknown-typed. - Functions can have several type parameters (
<A, B>), and generic callbacks pass precise types through. - If a type parameter appears only once, you probably don’t need it — use a concrete type or
unknown.