Lesson 4 of 9 · 24m
Conditional Types and infer: Pattern Matching at the Type Level
How conditional types distribute over unions, what infer really binds, and where type-level branching is worth the complexity.
Conditional types look intimidating because the syntax compresses three ideas into one line: a type test, a binding mechanism, and a branch. Read them as pattern matching over types and they become ordinary engineering. T extends U ? X : Y means: if values of type T can be assigned to type U, choose X; otherwise choose Y.
The useful part is usually infer
type AwaitedValue<T> = T extends Promise<infer V> ? V : T;
type A = AwaitedValue<Promise<string>>; // string
type B = AwaitedValue<number>; // numberinfer V introduces a type variable inside the true branch. TypeScript attempts to match the input against the pattern and solve for V. If it cannot match, the false branch wins.
A more realistic use is extracting the payload shape from a framework helper:
type QueryResult<T> = T extends { data: infer D; error: infer E }
? { data: D; error: E }
: never;Distribution over unions surprises everyone
When the checked type is a naked type parameter, conditional types distribute over unions:
type ToArray<T> = T extends unknown ? T[] : never;
type R = ToArray<string | number>; // string[] | number[]Not (string | number)[] — a union of arrays. Wrap the parameter in a tuple to disable distribution:
type ToArrayOnce<T> = [T] extends [unknown] ? T[] : never;
type R2 = ToArrayOnce<string | number>; // (string | number)[]This single rule explains half the mysterious conditional type behavior in production codebases.
Do not build a type-level compiler because you can
The type system is Turing-complete, which is a warning rather than an invitation. A twenty-line recursive conditional type may be clever, but a maintenance team will page you at 2 a.m. because hover tooltips have become a research project.
Good conditional types are small, named, and close to the domain. Bad ones are generic puzzle boxes with no tests.
Field notes
neveroften appears when distribution runs over an empty union or a branch collapses unexpectedly.- Use type tests (
type X = Assert<Equal<A, B>>) in.test-d.tsfiles or withtsdfor libraries. - Every
inferbinding is positional evidence; give the result a meaningful alias before exporting it. - If a conditional type is longer than the runtime function it describes, simplify the runtime contract first.
Was this lesson helpful?