Generics: The Universal Adapter

Generics: The Universal Adapter in TypeScript: The vehicle-recovery workshop keeps one good ratchet handle on the bench and a tray of sockets beside it.

The Analogy: The Ratchet and Its Sockets in a Recovery Workshop

The vehicle-recovery workshop keeps one good ratchet handle on the bench and a tray of sockets beside it. The handle on its own turns nothing: it has a square drive sticking out and no jaws, so until a socket is clipped on it cannot grip a single nut. Clip on the thirteen and it drives thirteen-millimetre nuts; clip on the seventeen and the same handle drives seventeens; clip on the nineteen and it drives nineteens. One mechanism, the ratchet with its pawl and its comfortable grip, is built once and then serves every size in the tray, because the part that decides the size is the socket you fit at the moment of use, not the handle.

The socket is chosen at the job, and once it is on, the tool is as specific as any fixed spanner. A thirteen socket on the drive will not turn a seventeen nut; it simply will not seat. That is the point of the tray rather than a single adjustable wrench: the adjustable spanner takes any size but rounds the corners off tight nuts because it never grips exactly, whereas the ratchet with the right socket grips a thirteen precisely, with the full certainty of a dedicated spanner, while still being the same handle that drove the seventeen a minute ago. You get one tool and the exact fit both at once.

The square drive is the whole arrangement's real rule. Every socket in the tray has the same square hole, and the handle has the same square peg, so any socket the shop owns will clip on and none will wobble. A socket cut for a different drive, a half-inch socket on a three-eighths handle, will not fit at all, and that refusal is a feature: it means that whatever is on the handle right now is guaranteed to be a socket the handle can actually turn. The drive square is the constraint that lets the one handle stay universal without ever holding something it cannot use.

The failure mode is forgetting that the universal handle is, at this instant, committed to one size. A fitter reaches for the ratchet still wearing the nineteen socket from the last axle, puts it to a thirteen nut without looking, and leans on it: either it does not seat and he forces it and rounds the nut, or he grabs the wrong socket from the tray in a hurry and drives a fastener to the wrong torque. The handle being able to fit any socket is exactly what hides the fact that it is fitted with one particular socket now, and a size fitted and forgotten does real damage that a single fixed spanner, which can only ever be its own size, never could.


Syntax or Core Structure

A generic function names a type it does not yet know, with a placeholder in angle brackets, and holds that placeholder consistent from parameter to return. <T> is the square drive: it will accept any type at the call, and whatever type it accepts on the way in is the exact type it hands back.

// src/adapter.ts
function identity<T>(value: T): T {
    return value;   // hands back exactly the type it was given
}

function wrapInArray<T>(item: T): T[] {
    return [item];
}

const code = identity("ratchet");   // T is string; code is string
const size = identity(13);          // T is number; size is number
const sizes = wrapInArray(19);      // T is number; sizes is number[]

console.log(code.toUpperCase(), size * 2);
console.log(sizes.length, sizes[0]);
// identity<number>("nineteen");    // refused: string is not assignable to number

Output:

RATCHET 26
1 19

Output (tsc, for the commented line):

error TS2345: Argument of type 'string' is not assignable to parameter of type 'number'.

code comes back typed string, so toUpperCase is available; size comes back number, so the arithmetic is allowed; sizes is number[], so length and the indexed read are typed. The last line is refused because an explicit <number> fixed the socket to number and a string will not seat on it. That preservation is the whole difference from any, which would have thrown the type away and let every one of these lines through unchecked.


Technical Depth: How the Placeholder Is Fixed, and What It Buys

The placeholder can be inferred from the argument or stated outright, more than one can run at once, and each keeps the type from input to output. What all three share is the guarantee any cannot give: the type that goes in is the type that comes out.

Inferred, or stated outright

Most calls let the compiler read the type argument off the value, the way the fitter just picks the socket that matches the nut. When there is no value to read it from, you state it, the way you would call for a specific socket by size.

// src/infer.ts
function collect<T>(...items: T[]): T[] {
    return items;
}

const asked = collect(2, 13, 19);        // T inferred as number
const named = collect<string>("m13");    // T stated: string

console.log(asked.length, asked[1] + asked[2]);
console.log(named[0].toUpperCase());

Output:

3 32
M13

asked reads its T straight off the arguments and is number[], so asked[1] + asked[2] is 13 + 19. named has no argument the compiler could read a useful type from once it is empty of hints, so <string> states it, and the element gains toUpperCase. Stating the type argument is also how you narrow a call that would otherwise infer something wider than you want.

More than one socket at once

A function can carry several placeholders, each fixed independently, and keep them straight from parameters to return. Two type parameters are two sockets on the bench, each matched to its own nut.

// src/pair.ts
function pair<A, B>(a: A, b: B): [A, B] {
    return [a, b];
}

function swap<A, B>(tuple: [A, B]): [B, A] {
    return [tuple[1], tuple[0]];
}

const p = pair("torque", 90);   // [string, number]
const q = swap(p);              // [number, string]

console.log(p[0], p[1]);
console.log(q[0], q[1]);

Output:

torque 90
90 torque

pair fixes A to string and B to number independently, so p is [string, number]. swap returns [B, A], so q is [number, string], and the compiler tracks that the number is now first: q[0] is typed number and q[1] typed string, with the values following the types exactly. Nothing was widened to a shared supertype; each slot kept its own identity through the swap.

Constraining what the socket may be

A bare <T> accepts anything, which means you can do nothing with it but pass it along, because the compiler knows nothing you can rely on. T extends ... is the drive square: it narrows what may be fitted so the body can use a known shape.

// src/constrain.ts
interface HasLength {
    length: number;
}

function longest<T extends HasLength>(a: T, b: T): T {
    return a.length >= b.length ? a : b;   // .length is guaranteed by the constraint
}

const word = longest("spanner", "wrench");   // T is string
const list = longest([1, 2, 3], [9, 8]);      // T is number[]

console.log(word, list.length);
// longest(5, 9);   // refused: number has no 'length'

Output:

spanner 3

Output (tsc, for the commented line):

error TS2345: Argument of type 'number' is not assignable to parameter of type 'HasLength'.

The constraint lets the body read .length safely, because every T is now guaranteed to have one; "spanner" at seven beats "wrench" at six, and [1, 2, 3] at three beats [9, 8] at two. And it still returns T, not HasLength, so list stays number[] and keeps .length typed. Pass a number, which has no length, and the drive square refuses it before the body ever runs.

What the placeholder keeps that any throws away

The reason to write <T> instead of reaching for any is that the type survives the call. The three columns below are the same identity function typed three ways.

Written asType of the resultMethods availableA wrong-type call
identity<T>(v: T): Tthe exact argument typeall of that type'srefused at compile time
identity(v: any): anyanyany name, uncheckedsilently accepted
identity(v: unknown): unknownunknownnone until narrowedaccepted, then unusable

The generic row is the only one that is both safe and usable: the result carries the argument's own type, so its methods are there and a wrong argument is caught. any is usable but unsafe, unknown is safe but inert until you narrow it. A generic is the socket that fits the nut exactly; any is the adjustable that rounds it off.


Real World Example: The Recovery Workshop Job Board

The workshop books jobs against bays and vehicles, and the summary needs the same shape of arithmetic over several fields: total minutes, total charge, the longest job, a count per vehicle. Writing sumBy, maxBy and groupCount once as generics means one tested helper serves every field and every record type, instead of a bespoke loop per column.

// src/board.ts
type Vehicle = "van" | "car" | "lorry";
type Bay = "bayA" | "bayB";
type Job = { ref: string; vehicle: Vehicle; bay: Bay; minutes: number; charge: number };

const JOBS: readonly Job[] = [
    { ref: "J1", vehicle: "van",   bay: "bayA", minutes: 40, charge: 120 },
    { ref: "J2", vehicle: "car",   bay: "bayA", minutes: 30, charge: 80 },
    { ref: "J3", vehicle: "lorry", bay: "bayB", minutes: 75, charge: 180 },
    { ref: "J4", vehicle: "van",   bay: "bayA", minutes: 35, charge: 90 },
    { ref: "J5", vehicle: "car",   bay: "bayB", minutes: 40, charge: 60 }
];

const VEHICLE_ORDER: readonly Vehicle[] = ["van", "car", "lorry"];
const BAY_ORDER: readonly Bay[] = ["bayA", "bayB"];
const CODES: readonly string[] = ["m13", "m17", "m19"];

function pad(text: string, width: number): string {
    return text.length >= width ? text : text + " ".repeat(width - text.length);
}

function sumBy<T>(items: readonly T[], pick: (item: T) => number): number {
    return items.reduce((total, item) => total + pick(item), 0);
}

function maxBy<T>(items: readonly T[], pick: (item: T) => number): T {
    return items.reduce((best, item) => (pick(item) > pick(best) ? item : best));
}

function groupCount<T, K extends string>(items: readonly T[], key: (item: T) => K): Record<K, number> {
    const out = {} as Record<K, number>;
    for (const item of items) {
        const k = key(item);
        out[k] = (out[k] ?? 0) + 1;
    }
    return out;
}

function board(jobs: readonly Job[]): string {
    const out: string[] = [];
    out.push(pad("BAY", 6) + pad("JOBS", 6) + pad("MINUTES", 9) + "CHARGE");
    for (const bay of BAY_ORDER) {
        const inBay = jobs.filter((j) => j.bay === bay);
        out.push(pad(bay, 6) + pad(String(inBay.length), 6)
            + pad(String(sumBy(inBay, (j) => j.minutes)), 9)
            + String(sumBy(inBay, (j) => j.charge)));
    }
    const longest = maxBy(jobs, (j) => j.minutes);
    const counts = groupCount(jobs, (j) => j.vehicle);
    const byVehicle = VEHICLE_ORDER
        .filter((v) => (counts[v] ?? 0) > 0)
        .map((v) => v + " x" + String(counts[v]));
    out.push("jobs: " + String(jobs.length)
        + ", minutes: " + String(sumBy(jobs, (j) => j.minutes))
        + ", charge: " + String(sumBy(jobs, (j) => j.charge)));
    out.push("longest: " + longest.ref + " " + longest.vehicle + " "
        + String(longest.minutes) + " min");
    out.push("by vehicle: " + byVehicle.join(", "));
    return out.join("\n");
}

console.log(board(JOBS));
console.log(sumBy(CODES, (c) => c.length));

Output:

BAY   JOBS  MINUTES  CHARGE
bayA  3     105      290
bayB  2     115      240
jobs: 5, minutes: 220, charge: 530
longest: J3 lorry 75 min
by vehicle: van x2, car x2, lorry x1

Output (the reused helper on a different type):

9

Read the board against the sockets. sumBy is called five times over three different fields, minutes and charge on the whole list and on each bay's slice, and every call is the same tested reducer with a different pick: the generic is the handle, the selector is the socket. bayA holds three jobs totalling 105 minutes and 290, bayB two totalling 115 and 240, and the footer's 220 and 530 are the same helper run over the unfiltered list. maxBy picks J3 because 75 minutes is the largest, and groupCount tallies the vehicles, which VEHICLE_ORDER then prints in a fixed order so the line never depends on object-key iteration.

The last line of the program is the point of generics in one call. sumBy(CODES, (c) => c.length) runs the identical helper over an array of string, not Job, summing 3 + 3 + 3 to 9. Nothing about sumBy was written for jobs; it was written for "any T and a way to read a number out of it", so it serves a list of strings as readily as a list of job records. One reducer, tested once, covers every case the shape fits.

The program has real defects, and they sit in the helpers rather than the data. groupCount builds its accumulator with {} as Record<K, number>, a cast that tells the compiler every key is present when the object starts empty, so counts[v] is typed number while a vehicle with no jobs would really be undefined; the ?? 0 guard is doing load-bearing work the type claims is unnecessary, and drop it and a zero-count vehicle would print x undefined. maxBy calls reduce with no initial value, so on an empty array it throws at runtime even though its signature promises to always return a T: the type is a lie about a partial function. sumBy constrains nothing about the numbers it adds, so a pick that returns NaN or overflows Number.MAX_SAFE_INTEGER produces a wrong total in silence. And charge prints as a bare 530 with no currency unit, the same figure-without-a-label trap as before, readable as pounds, pence or nothing in particular.


Common Mistakes

  1. Reaching for any where a generic belongs: function first(a: any[]): any throws the element type away, so the result has no methods checked and a wrong use is caught by nothing; function first<T>(a: T[]): T keeps it.
  2. Adding a type parameter that appears only once: function log<T>(x: T): void gains nothing over function log(x: unknown): void, because a placeholder used in one position relates no two things; a generic earns its keep by linking input to output.
  3. Leaving T unconstrained and then using a property on it: t.length on a bare <T> is refused, because nothing guarantees the property; add T extends HasLength.
  4. Confusing the constraint with the return type: function pick<T extends HasLength>(t: T): HasLength widens the result to the constraint and loses the caller's real type; return T to keep it.
  5. Casting the accumulator with {} as Record<K, V>: it asserts every key exists when the object is empty, so an indexed read is typed non-undefined while the runtime value is missing; keep the ?? default and know it is real.
  6. Calling reduce with no seed in a helper that promises a total return: an empty array throws, contradicting the signature; pass an initial value, or type the return as T | undefined.
  7. Writing overlapping type parameters that should be one: function samePair<A, B>(a: A, b: B) when both must be the same type should be <T>(a: T, b: T), or the compiler will not stop a mismatched pair.
  8. Over-parameterising a signature: five type parameters where two would do makes call sites unreadable and inference fragile; add a placeholder only when two positions genuinely must agree.
  9. Assuming inference always finds the type you meant: an empty array infers unknown[] or never[] with no hint, so state collect<string>() when there is nothing for the compiler to read.

Best Practices

  • Reach for a generic whenever the input type should flow to the output: identity, wrappers, mappers and reducers all keep the caller's type instead of erasing it to any.
  • Give a type parameter at least two jobs: it should tie a parameter to the return, or one parameter to another; a placeholder used once is a sign unknown was the right type.
  • Constrain with extends the moment the body touches a property: the constraint is what lets you read .length or .id safely, and it still returns the caller's own narrower type.
  • Return T, not the constraint: <T extends Named>(t: T): T preserves the exact type; returning Named throws away everything the constraint did not mention.
  • Let inference work, and state the type argument only when it cannot: an empty collection or an ambiguous literal is where an explicit <T> earns its place.
  • Name multiple parameters for what they are: <Key, Value> reads at the call site where <T, U, V> does not, and it makes a swapped argument obvious.
  • Type a partial helper honestly: if maxBy can be handed an empty list, its return is T | undefined, and the call site should handle the undefined rather than trust a signature that lies.
  • Keep one tested generic helper rather than a loop per field: sumBy, groupCount and the like are written and checked once and then serve every record type and every column.

Practice Exercises

  1. The Identity and the Wrapper: Write identity<T>(v: T): T and wrapInArray<T>(v: T): T[], call each on a string and a number, and confirm in one line each why the result keeps its type where an any version would not.
  2. The Constrained Longest: Write longest<T extends { length: number }>(a: T, b: T): T, call it on two strings and two arrays, then call it on two numbers and read the error; explain why the return is T and not { length: number }.
  3. The Two-Parameter Swap: Write swap<A, B>(t: [A, B]): [B, A], apply it to ["torque", 90], and show by a hand-trace that the result is typed [number, string] with the values in the new order.
  4. The Honest maxBy: Take board.ts, change maxBy to return T | undefined and seed the reduce correctly, handle the empty-list case at the call site, and hand-trace what the "longest" line prints when JOBS is empty.