The Analogy: The Weighbridge at a Quarry Gate
A working quarry has a weighbridge at its gate: a steel platform that every laden lorry drives onto before it leaves. The bridge asks one question, is the gross weight over the axle limit for this class of lorry, and the answer sends the lorry down one of two routes. Under the limit, it goes straight to the exit road. Over the limit, it is diverted to the reload bay to shed the excess. Same platform, same single question, two possible destinations decided entirely by what drove on. A conditional type is that weighbridge, running at compile time on a type instead of a lorry: T extends Limit ? Pass : Divert asks whether T is assignable to Limit and yields one of two types accordingly.
The word to be careful with is extends. On the weighbridge it does not mean the lorry is descended from some ancestral lorry; it means the lorry meets the criterion, its weight is within the tested class. In a conditional type extends means exactly that, "is assignable to", not "inherits from". A specific literal type like "granite" is assignable to the wider type string, so "granite" extends string takes the true branch, in the same way a lorry weighing three tonnes satisfies a five-tonne limit. Reading extends as inheritance is the single most common way people misjudge which branch a conditional will take.
A single weighbridge only sorts one lorry at a time, but a convoy changes the picture, and this is where the quarry's real cleverness lies. When a whole convoy of mixed lorries is sent over the bridge as a group, the bridge does not weigh them lashed together as one combined mass. It weighs each lorry individually and routes each to its own destination, then the results are gathered back into a group at the far end. A conditional type behaves identically when the thing being checked is a bare type parameter handed a union: it does not test the union as one lump, it tests each member separately and unions the individual results back together. This per-member behaviour, called distribution, is what makes a two-line conditional able to filter a union, and it is the feature that surprises everyone the first time they meet it.
The failure mode is forgetting that distribution happens, or forgetting that it can be switched off. An operator who assumes the convoy was weighed as a block will misread every routing decision, exactly as a developer who forgets distribution will expect one answer from a union and be baffled to get a union of answers back. The quarry can force whole-convoy weighing by loading the lorries onto a single flatbed first, so the bridge sees one indivisible load; in a conditional type you do the same by wrapping both sides in a one-element tuple, [T] extends [U], which stops the parameter being naked and makes the union get tested as a single unit. Knowing which mode you are in, per-member or whole-union, is the whole art of writing conditionals that mean what you think they mean.
Syntax or Core Structure
A conditional type has the shape T extends U ? X : Y. Because the branches are types, not values, you cannot see them at runtime directly; the usual way to make the result observable is to have a value's type flow through the conditional and then print a plain value that the type controls. This example uses a conditional inside a return type so the returned value's shape depends on the argument.
// src/weigh.ts
// If T is an array, unwrap its element type; otherwise keep T
type Unwrap<T> = T extends Array<infer U> ? U : T;
function first<T>(value: T): Unwrap<T> {
if (Array.isArray(value)) {
return value[0] as Unwrap<T>;
}
return value as Unwrap<T>;
}
const a: number = first([10, 20, 30]); // Unwrap<number[]> = number
const b: string = first("granite"); // Unwrap<string> = string
console.log(a);
console.log(b);
console.log(a + ("granite".length));
Output:
10
granite
17
The conditional T extends Array<infer U> ? U : T does the routing. For first([10, 20, 30]), T is number[], which matches Array<infer U> with U inferred as number, so the return type is number and the value is the first element, 10. For first("granite"), T is string, which is not an array, so the false branch keeps T and the whole string comes back. The final line reads a as 10 and adds the length of "granite", which is 7, giving 10 + 7 = 17. The infer keyword is the part worth noting: it declares a type variable inside the extends clause and captures whatever the compiler matched there, which is how the built-in ReturnType and Parameters are written.
Technical Depth: Distribution, and Turning It Off
The behaviour that makes conditional types powerful is distribution over unions, and it is also the behaviour that trips people up. When the checked type is a bare type parameter and you hand it a union, the conditional runs once per union member rather than once on the whole union, and the results are unioned back together, exactly like the weighbridge weighing each lorry in a convoy separately.
Distribution builds the standard filters
// src/distribute.ts
// A naked T over a union distributes: runs per member
type OnlyStrings<T> = T extends string ? T : never;
type Mixed = "north" | 3 | "south" | 7 | "east";
type Words = OnlyStrings<Mixed>; // "north" | "south" | "east"
// runtime check of the same idea, to make it observable
const values: (string | number)[] = ["north", 3, "south", 7, "east"];
const words = values.filter((v): v is string => typeof v === "string");
console.log("kept " + words.length);
console.log(words.join(","));
Output:
kept 3
north,south,east
At the type level, OnlyStrings<Mixed> tests each member of the union on its own: "north" is a string so it survives, 3 is not so it becomes never, and because never disappears from a union the result is just the three string literals. This is exactly how the built-in Extract<T, U> is defined, T extends U ? T : never, and its sibling Exclude<T, U> swaps the branches to T extends U ? never : T. The runtime filter mirrors the type-level filter: five values in, the three strings kept, giving kept 3 and north,south,east.
The bracket trick switches distribution off
Wrapping both sides of the check in a single-element tuple makes the parameter no longer naked, so the union is tested as one indivisible unit, the flatbed that forces whole-convoy weighing.
// src/bracket.ts
// Naked: distributes over the union member by member
type IsStringLoose<T> = T extends string ? "yes" : "no";
// Bracketed: tests the whole union as one unit
type IsStringStrict<T> = [T] extends [string] ? "yes" : "no";
// Observe the difference by driving values whose types we know
function loose(label: IsStringLoose<string>): string {
return label; // "yes"
}
function strict(label: IsStringStrict<string | number>): string {
return label; // "no" -- the whole union is not assignable to string
}
console.log(loose("yes"));
console.log(strict("no"));
Output:
yes
no
For IsStringLoose<string> the single member string takes the true branch, so the parameter type is the literal "yes". The interesting case is IsStringStrict<string | number>: because the check is bracketed, the compiler asks whether the entire union string | number is assignable to string, which it is not, so the result is "no". Had that been written naked as IsStringLoose<string | number>, distribution would have produced "yes" | "no" rather than a single answer, which is rarely what you want from a "is this a string" test. There is one more edge worth remembering: never is itself an empty union, so a distributive conditional handed never has no members to iterate and returns never without ever running either branch.
The built-ins are just conditionals
Almost every clever utility type in the standard library is a conditional type you could have written yourself, and reading their definitions is the fastest way to get fluent. The table lays out the common ones with their one-line definitions.
| Utility | Definition | Result on the example |
|---|---|---|
| Exclude<T, U> | T extends U ? never : T | drops matching members |
| Extract<T, U> | T extends U ? T : never | keeps matching members |
| ReturnType<F> | F extends (...a) => infer R ? R : never | the return type |
| Parameters<F> | F extends (...a: infer P) => any ? P : never | the parameter tuple |
| NonNullable<T> | T & {} | strips null and undefined |
// src/builtins.ts
type Handler = (id: number, name: string) => boolean;
type Args = Parameters<Handler>; // [number, string]
type Out = ReturnType<Handler>; // boolean
function run(fn: Handler, args: Args): Out {
return fn(args[0], args[1]);
}
const ok = run((id, name) => id > 0 && name.length > 0, [5, "ada"]);
console.log(ok);
console.log(String(ok).length);
Output:
true
4
Parameters<Handler> uses infer P to capture the parameter list as the tuple [number, string], and ReturnType<Handler> uses infer R to capture boolean. The run function then takes exactly that tuple and returns exactly that type, so the call with [5, "ada"] evaluates 5 > 0 && "ada".length > 0 to true. Printing true and then String(true).length, which is the length of the four-character string "true", gives 4. None of these utilities involve compiler magic; each is a ternary and, where needed, an infer.
Real World Example: A Charge Table Whose Rate Depends on Load Class
The quarry bills each departing lorry, and the rate depends on its load class: a fixed gate fee for an empty lorry, and a per-tonne rate for a laden one. Rather than pass the whole thing through untyped, a conditional type decides, per class, what data each charge record must carry, so an empty record cannot accidentally claim a tonnage and a laden record cannot omit one. The conditional produces the argument shape, and the compiler enforces it at every call site.
// src/charges.ts
type LoadClass = "empty" | "laden";
// A conditional picks the payload shape per class
type Charge<C extends LoadClass> =
C extends "empty"
? { cls: C; gateFee: number }
: { cls: C; tonnes: number; ratePerTonne: number };
function amount<C extends LoadClass>(charge: Charge<C>): number {
if (charge.cls === "empty") {
return charge.gateFee;
}
return charge.tonnes * charge.ratePerTonne;
}
function pad(text: string, width: number): string {
const gap = width - text.length;
return text + " ".repeat(gap > 0 ? gap : 0);
}
const charges: Array<Charge<"empty"> | Charge<"laden">> = [
{ cls: "empty", gateFee: 5 },
{ cls: "laden", tonnes: 6, ratePerTonne: 20 },
{ cls: "laden", tonnes: 3, ratePerTonne: 20 },
{ cls: "empty", gateFee: 5 },
];
let total = 0;
console.log("charges: " + charges.length);
console.log(pad("CLS", 8) + "AMOUNT");
for (const c of charges) {
const due = amount(c);
total += due;
console.log(pad(c.cls, 8) + due);
}
console.log("total: " + total);
Output:
charges: 4
CLS AMOUNT
empty 5
laden 120
laden 60
empty 5
total: 190
Trace the four charges. The conditional Charge<C> gives an "empty" record the field gateFee and a "laden" record the fields tonnes and ratePerTonne, and amount narrows on charge.cls to read the right ones. The first empty lorry pays its gateFee of 5. The first laden lorry pays 6 * 20 = 120, the second laden pays 3 * 20 = 60, and the last empty pays 5 again. The four amounts sum to 5 + 120 + 60 + 5 = 190. Because the class field discriminates the union, reading gateFee on a laden record or tonnes on an empty one would not compile, so a malformed charge is caught before it can reach the total.
The value of the conditional here is that one type parameter drives the entire record shape. Add a third class such as "oversize" to LoadClass and extend the conditional, and every function that builds or consumes a Charge is forced by the compiler to account for it, rather than silently defaulting a missing field to zero. The billing logic and the data shape stay locked together through a single source of truth.
That same design carries a real flaw worth stating plainly. The conditional Charge<C> has exactly two arms, so it silently treats any class that is not "empty" as laden; the moment LoadClass gains a third member, that new class falls through into the laden branch and is billed per-tonne by accident, with no error at the definition site because the false arm is a catch-all rather than an exhaustive match. A safer design would chain the conditional per class and end in never, forcing a compile error on any unhandled class. Two smaller limits sit alongside: the model assumes a laden lorry always carries both tonnes and ratePerTonne, so it cannot represent a laden lorry billed at a flat rate; and amount trusts the numbers without bound, so a negative tonnes from bad upstream data would produce a negative charge that the type system does nothing to prevent.
Common Mistakes
- Reading
extendsas class inheritance. In a conditional it means "is assignable to", so"granite" extends stringis true because the literal is assignable to the wider type. - Forgetting distribution over unions. A naked
T extends X ? ... : ...handed a union runs per member, soToArray<string | number>isstring[] | number[], not(string | number)[]. - Expecting a single answer from a distributed union.
IsString<string | number>distributes to"yes" | "no"; bracket the check as[T] extends [string]when you want the union treated as one unit. - Assuming
neverruns a branch.neveris an empty union, so a distributive conditional handedneverreturnsneverwithout evaluating either arm. - Using
anyin the false branch instead ofnever.anysilently swallows the non-matching cases, whereasnevercollapses them so wrong inputs disappear cleanly. - Writing a two-arm conditional over a union that will grow. A catch-all false branch treats every future member as the false case, so a new union member is mishandled with no error at the definition.
- Nesting five conditionals deep when a mapped type or an overload is clearer. A signature that type-checks but nobody can read is still a liability.
- Reaching for
inferwhere indexed access would do. If you only need a known property's type,T["field"]is simpler and clearer than aninfer-based conditional. - Hitting "type instantiation is excessively deep" and adding
any. The fix is to simplify or bound the recursion, not to disable the check withany.
Best Practices
- Name intermediate conditionals rather than nesting one giant ternary. A
type IsAsync<F> = ...alias reads far better than a five-level chain inlined into a signature. - Use
neverfor the "no match" branch. Bad cases then collapse and vanish from the resulting union instead of leaking through asany. - Reach for a built-in before writing your own.
Exclude,Extract,ReturnType,Parameters, andNonNullablecover most needs and are instantly recognisable. - Bracket the check with
[T] extends [U]when you want the whole union tested. It is the deliberate way to turn distribution off. - Chain conditionals per case and end in
neverfor closed unions. An exhaustive chain turns a new, unhandled member into a compile error instead of a silent misclassification. - Keep conditionals shallow at API boundaries. Push the cleverness into named internal aliases and expose a signature a caller can actually read.
- Test type-level code with equality assertions. A
type Check = Expect<Equal<Actual, Expected>>helper, or simply hovering in the editor, catches a conditional that yields the wrong branch. - Prefer indexed access over
inferwhen both work. Useinferfor genuinely structural extraction, not for pulling out a property whose key you already know.
Practice Exercises
- The Weighbridge. Write
type ElementOf<T>that returnsUfor an arrayU[]and leavesTunchanged otherwise, then confirm its result onstring[],number, andboolean[][]by hovering each. - Rebuild the Filters. Implement
MyExclude<T, U>andMyExtract<T, U>from scratch using distribution, and check they match the built-ins on the union"a" | "b" | "c". - Switch Distribution Off. Write both
IsExactlyString<T>bracketed andIsStringLoose<T>naked, feed eachstring | number, and explain in a comment why one yields a single answer and the other a union. - The Payload Shape. Given
type Events = { click: { x: number; y: number }; close: undefined }, write anemitwhose argument list is decided by a conditional so thatemit("close")takes one argument andemit("click", { x, y })takes two.