Generic Constraints: Setting the Door Height

Generic Constraints: Setting the Door Height in TypeScript: The vehicle deck of a roll-on roll-off ferry is generic in the truest sense: it does not care what…

The Analogy: The Ferry's Vehicle Deck

The vehicle deck of a roll-on roll-off ferry is generic in the truest sense: it does not care what drives aboard. Cars, vans, lorries, coaches, a refrigerated trailer -- the deck takes them all, because a deck that only accepted one make of van would be a useless deck. But at the top of the ramp there is a bar, the clearance under the deckhead, and a marshaller standing beside it. Anything that clears the bar may board, whatever it is; anything that does not is turned away at the ramp. The bar does not narrow the deck to a single kind of vehicle. It guarantees one property -- height -- of every vehicle that rolls on.

That is exactly what a constraint is. A plain generic <T> is a deck with no bar and no marshaller: it accepts literally anything, which means the crew below can assume nothing about what they are carrying and dare not reach for a roof or a chassis rail that might not be there. Writing <T extends { height: number }> installs the bar. The deck is still open to a huge range of vehicles, but now the crew knows every one of them has a measured height they can read and act on, because nothing that lacked one ever got past the ramp.

There is a second gate, and it is the one that matters most in a swell. Every vehicle on the deck must be lashed down, and a lashing chain can only be shackled to a lashing eye the vehicle actually carries. The marshaller does not invent an anchor point; he reads the eyes welded to that particular chassis and hooks to those. Name a fitting the vehicle does not have and there is simply nothing to shackle to. That is the keyof constraint: K extends keyof T says the key you hand in must name a real fitting on this type, so you can only ever lash to a point that exists. And when the booking does not state a vehicle class at all, the standing orders assume "car" -- a safe default that still clears the bar -- which is what a default type parameter does.

The failure mode is a check that is nodded through rather than actually made. A marshaller who waves a high-roof van aboard on the strength of the booking alone, without watching it pass under the deckhead, gets a roof box wedged against a deck beam at the worst possible moment, with the whole queue stopped on the ramp behind it. A crew that shackles a chain to a chrome trim strip because it looks like a lashing eye finds, in the first big roll, that the strip was never rated: the chain tears free and four tonnes of lorry starts to move. A constraint that is assumed instead of enforced, or a fitting that looks right but is not the real thing, is how a deck that should have been safe quietly becomes a deck that is not.


Syntax or Core Structure

A constraint is written with extends: <T extends Tall> means "any T, provided it is assignable to Tall". Inside the function you may then use every member the constraint promises, and TypeScript refuses any call whose argument does not clear the bar.

// src/clearance.ts
interface Tall { height: number }

// accepts any type that carries a numeric height
function clears<T extends Tall>(item: T, limit: number): boolean {
    return item.height <= limit;
}

const van = { plate: "V1", height: 260 };
const car = { plate: "C1", height: 150 };

console.log(clears(van, 400), clears(car, 400));
console.log(clears(van, 250));
// clears(42, 400);   // refused: a number has no 'height'

Output:

true true
false

Output (tsc, for the commented line):

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

Both van and car clear a 400 limit, so the first line is true true; the van's 260 does not clear a 250 limit, so the second is false. The commented call is refused before it runs, because 42 is a number and a number has no height to read -- it never clears the bar. Note that van carries an extra plate field and is still accepted: the constraint asks only that T be assignable to Tall, not that it match Tall exactly, so any vehicle with at least a numeric height may board.


Technical Depth: Which Fitting, What Default, and Two Bars at Once

The height bar is only the plainest constraint. The more powerful ones tie one type parameter to another, supply a fallback when a caller stays silent, and demand that a type clear two bars at the same time.

K extends keyof T ties the key to the object

The most useful constraint in TypeScript relates two type parameters: K extends keyof T says the key must name a real property of T. It is how every typed get, set, sortBy and groupBy helper is built, and it turns a mistyped key into a compile error instead of a runtime undefined.

// src/lash.ts
function readAt<T, K extends keyof T>(obj: T, key: K): T[K] {
    return obj[key];   // the return type is exactly T[K]
}

const lorry = { plate: "L1", axles: 3, refrigerated: true };

const p = readAt(lorry, "plate");    // typed string
const a = readAt(lorry, "axles");    // typed number
// readAt(lorry, "wheels");          // refused: not a fitting on this vehicle

console.log(p, a);

Output:

L1 3

Output (tsc, for the commented line):

error TS2345: Argument of type '"wheels"' is not assignable to parameter of type '"plate" | "axles" | "refrigerated"'.

readAt reads plate and axles and returns each at its true type -- string and number -- because the return is annotated T[K], the type of that one property. Ask for "wheels" and the compiler lists the fittings the vehicle actually has and refuses, exactly as the marshaller finds no such lashing eye. The key is checked against keyof T, so a typo cannot compile.

A default type parameter fills the silent booking

Constraints say what is allowed; a default says what to assume when the caller names nothing. The default must itself satisfy the constraint, just as the assumed "car" must still clear the bar.

// src/standing.ts
type Vehicle = "car" | "van" | "lorry";

interface Booking<V extends Vehicle = "car"> {
    ref: string;
    vehicle: V;
}

const unstated: Booking = { ref: "B1", vehicle: "car" };        // V defaults to "car"
const stated: Booking<"lorry"> = { ref: "B2", vehicle: "lorry" };

console.log(unstated.vehicle, stated.vehicle);

Output:

car lorry

unstated names no type argument, so V falls back to "car" and the object must set vehicle: "car"; stated fixes V to "lorry". The default is written = "car" after the constraint, and because "car" is a member of Vehicle it satisfies extends Vehicle -- a default that broke its own constraint would be an error at the declaration, not the call.

An intersection asks a type to clear two bars

A constraint can be an intersection: T extends A & B admits only types that are assignable to both. It is how you demand two independent properties -- a height and a weight, an id and a timestamp -- without inventing a named interface for the pair.

// src/twobars.ts
interface Tall { height: number }
interface Heavy { weight: number }

function canBoard<T extends Tall & Heavy>(item: T): boolean {
    return item.height <= 400 && item.weight <= 5000;
}

const trailer = { plate: "T1", height: 380, weight: 4200 };

console.log(canBoard(trailer));
// canBoard({ plate: "X", height: 300 });   // refused: no 'weight'

Output:

true

trailer clears both bars -- 380 under 400 and 4200 under 5000 -- so canBoard returns true. The commented call carries a height but no weight, so it is not assignable to Tall & Heavy and is refused: an intersection constraint is only cleared by a type that has every member of both sides.

The constraint forms at a glance

The common constraints, what each admits, and what it lets you do inside the body.

ConstraintAdmitsGrants inside the body
T extends objectany non-primitivesafe to spread and assign, not to index freely
T extends { length: number }strings, arrays, anything measuredreading .length
K extends keyof Ta real key of Tindexing obj[key] at type T[K]
T extends unknown[]any arrayT[number] for the element type
T extends (...args: never[]) => unknownany functionpairing with ReturnType<T>
T extends stringa string, literal preservedkeeping the exact literal, not widened
T extends A & Btypes assignable to bothevery member of A and of B

The row to keep in mind is K extends keyof T: it is the one that ties two parameters together, and the one that converts a typo into a build error rather than a silent undefined at three in the morning.


Real World Example: The Ferry Load Plan

The deck officer prints a load plan for every crossing: the vehicles aboard, their lanes, the weight in each lane, and the heaviest single unit. The helpers that build it are generic on purpose, because the same heaviest and the same count-by-key must serve the vehicle deck, the container list on the deck above, and the passenger manifest, and rewriting them per shape is how three copies drift apart. Each helper carries exactly the constraint it needs and no more: heaviest asks only that its items be weighed, and the counter asks only that its key be a real key of the item.

// src/deck.ts
type Lane = "port" | "stbd" | "centre";

interface Vehicle {
    plate: string;
    kind: string;
    lane: Lane;
    weight: number;
}

const FLEET: readonly Vehicle[] = [
    { plate: "V1", kind: "van",   lane: "port",   weight: 1400 },
    { plate: "C1", kind: "car",   lane: "stbd",   weight: 1200 },
    { plate: "L1", kind: "lorry", lane: "centre", weight: 4200 },
    { plate: "C2", kind: "car",   lane: "stbd",   weight: 1200 },
    { plate: "B1", kind: "coach", lane: "port",   weight: 2800 }
];

const LANE_ORDER: readonly Lane[] = ["port", "stbd", "centre"];

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

// constrained to anything weighed; returns the whole item at type T
function heaviest<T extends { weight: number }>(items: readonly T[]): T {
    let top = items[0];
    for (const item of items) {
        if (item.weight > top.weight) { top = item; }
    }
    return top;
}

// K must name a real key of T; counts by the stringified value at that key
function countByKey<T, K extends keyof T>(items: readonly T[], key: K): Map<string, number> {
    const out = new Map<string, number>();
    for (const item of items) {
        const value = String(item[key]);
        out.set(value, (out.get(value) ?? 0) + 1);
    }
    return out;
}

function plan(fleet: readonly Vehicle[]): string {
    const out: string[] = [];
    const total = fleet.reduce((sum, v) => sum + v.weight, 0);
    out.push("vehicles: " + String(fleet.length) + ", total weight: " + String(total) + " kg");
    out.push(pad("PLATE", 6) + pad("KIND", 8) + pad("LANE", 8) + "WEIGHT");
    for (const v of fleet) {
        out.push(pad(v.plate, 6) + pad(v.kind, 8) + pad(v.lane, 8) + String(v.weight));
    }
    const counts = countByKey(fleet, "lane");
    const byLane = LANE_ORDER
        .filter((lane) => (counts.get(lane) ?? 0) > 0)
        .map((lane) => lane + " x" + String(counts.get(lane)));
    const laneWeight = LANE_ORDER
        .map((lane) => [lane, fleet.filter((v) => v.lane === lane).reduce((s, v) => s + v.weight, 0)] as const)
        .filter(([, w]) => w > 0)
        .map(([lane, w]) => lane + " " + String(w));
    const top = heaviest(fleet);
    out.push("by lane: " + byLane.join(", "));
    out.push("lane weight: " + laneWeight.join(", "));
    out.push("heaviest: " + top.plate + " " + top.kind + " " + String(top.weight) + " kg");
    return out.join("\n");
}

console.log(plan(FLEET));

Output:

vehicles: 5, total weight: 10800 kg
PLATE KIND    LANE    WEIGHT
V1    van     port    1400
C1    car     stbd    1200
L1    lorry   centre  4200
C2    car     stbd    1200
B1    coach   port    2800
by lane: port x2, stbd x2, centre x1
lane weight: port 4200, stbd 2400, centre 4200
heaviest: L1 lorry 4200 kg

Read the plan against its constraints. heaviest is declared <T extends { weight: number }>, so inside the loop it may compare item.weight on any argument, and it returns the whole item at type T, which is why the last line can print L1's plate and kind and not just its weight: the constraint promised a weight to read, and the type parameter carried the rest of the vehicle through untouched. countByKey is <T, K extends keyof T>, so the call countByKey(fleet, "lane") is checked -- "lane" is a real key of Vehicle -- and a call with "colour" would be refused at compile time. The lane tally reads port x2, stbd x2, centre x1, and the heaviest is the 4200 kg lorry.

Those two constraints are the smallest that do the job, and that is deliberate. heaviest did not ask for Vehicle; it asked for { weight: number }, so the same function sorts containers and cargo pallets, anything with a weight, without a second copy. The key parameter did not take a string; it took K extends keyof T, so the compiler autocompletes the real fittings and rejects a mistyped one, turning a class of runtime undefined into a build error. Constrain to the structural minimum and one helper serves every weighed list on the ship; over-constrain to Vehicle and it serves exactly one deck.

The plan has genuine defects, and the sharpest is in heaviest. It reads items[0] with no guard and the signature promises to return a T, but handed an empty array it returns undefined at runtime while the type still claims a T, so the caller's top.plate throws with a value the types swore could not exist -- the constraint guaranteed each item has a weight but said nothing about the array being non-empty, and a truthful signature would return T | undefined. countByKey is safe here only because Lane is a string union: it counts by String(item[key]), so pointed at an object-valued key it would collapse every distinct object to "[object Object]" and silently merge the buckets. And the lane weight could not be written as a fully generic sumByKey<T, K extends keyof T>, because keyof T constrains the key but not the value at that key -- T[K] is not guaranteed to be a number you can add -- so the total is a hand-written reduce over LANE_ORDER, which means a fourth lane added to the Lane union but forgotten in LANE_ORDER would vanish from both summaries with no error at all, and the filter(w > 0) further hides any lane that exists but is empty, so the report cannot tell "no such lane" from "lane carrying nothing".


Common Mistakes

  1. Reaching for any to silence a constraint error: the error was telling you a property might be absent; any hides that instead of adding the extends { ... } that guarantees it.
  2. Reading a property off an unconstrained <T>: function first<T>(x: T) { return x.length; } will not compile, because a bare T could be a number; add T extends { length: number }.
  3. Over-constraining to a full named type: T extends Vehicle when the body only reads weight locks out containers and pallets; constrain to { weight: number }, the narrowest shape that works.
  4. Typing a key parameter as string: function get(obj: Thing, key: string) lets a typo through to a runtime undefined; K extends keyof T turns the same typo into a build error.
  5. Confusing generic extends with class inheritance: in <T extends Tall> it means "is assignable to Tall", not "is a subclass of"; a plain object literal with a height satisfies it.
  6. Assuming a default type parameter can skip the constraint: <V extends Vehicle = "bike"> is an error, because the default "bike" must itself be assignable to Vehicle.
  7. Writing <T>(x: T) => x in a .tsx file: the compiler reads <T> as a JSX tag; write <T,>(x: T) => x with the trailing comma to disambiguate.
  8. Believing the constraint survives to runtime: extends is erased at compile time, so a value that was never checked -- an empty array, a null slipped in through any -- still reaches the body unguarded.
  9. Trying to sum item[key] under K extends keyof T: keyof constrains the key but not the value type, so T[K] need not be a number; a generic sumByKey needs a value constraint the key alone cannot give.

Best Practices

  • Constrain to the structural minimum: ask for { weight: number }, not the whole Vehicle, so the helper serves every shape that has what the body actually reads.
  • Prefer K extends keyof T over string for any key parameter: it converts a mistyped key from a silent runtime undefined into a compile error, and gives callers autocomplete.
  • Return T | undefined when the input may be empty: a heaviest or first over a possibly-empty array should say so in its type rather than promise a T it cannot always deliver.
  • Give type parameters meaningful names once there are more than two: TItem and TKey read where T and K and U blur together in a public signature.
  • Take readonly T[] for input arrays: it tells callers the helper will not mutate their list and lets them pass a readonly array without a cast.
  • Reach for a default type parameter for the common case: <V extends Vehicle = "car"> keeps the frequent call ergonomic while the rare call still names its type.
  • Combine shapes with an intersection instead of a throwaway interface: T extends Tall & Heavy demands both properties without a named TallAndHeavy that exists only to be extended once.
  • Let inference do the work at the call site: annotate the constraint on the declaration, then call heaviest(fleet) without a type argument and let TypeScript fill T from the array.

Practice Exercises

  1. The Clearance Check: Write fits<T extends { height: number }>(item: T, limit: number): boolean and call it with a van object and a car object, then try to call it with a bare number and read the compiler error.
  2. The Safe Reader: Implement readAt<T, K extends keyof T>(obj: T, key: K): T[K] over a config object, confirm the return type is exact for two different keys, and show that a misspelled key fails to compile.
  3. The Empty Deck: Call heaviest on an empty array, observe that it returns undefined at runtime despite the T return type, then fix the signature to T | undefined and handle the gap at the call site.
  4. The Weighed Sum: Write a totalWeight<T extends { weight: number }>(items: readonly T[]): number and verify it against the plan's figures, then explain why the same cannot be written as a generic sumByKey<T, K extends keyof T>.