Chapter 5: Conditional Types, Distribution and infer
Runnable examples: examples/ch05-conditional-types.ts
Conditional types are if statements for types:
type IsString<T> = T extends string ? true : false;
Read T extends U as “is T a subset of U?” (Chapter 1), not as class inheritance.
Distribution: the rule that surprises everyone
When the checked type is a naked type parameter and you pass a union, the conditional is applied to each member separately, and the results are unioned:
type ToArray<T> = T extends unknown ? T[] : never;
type A = ToArray<string | number>; // string[] | number[], not (string | number)[]
This is exactly how the built-in Exclude works:
type MyExclude<T, U> = T extends U ? never : T;
type B = MyExclude<"a" | "b" | "c", "a">; // "b" | "c"
Each member is tested; members that match become never, and never disappears from unions.
Turning distribution off
Wrap both sides in a one-element tuple so the checked type is no longer naked:
type ToArrayNonDist<T> = [T] extends [unknown] ? T[] : never;
type C = ToArrayNonDist<string | number>; // (string | number)[]
The never trap
never is the empty union. Distributing over zero members gives zero results, so:
type D = IsString<never>; // never, not false
To test for never, disable distribution: [T] extends [never] ? true : false.
infer: pattern matching on types
Inside the extends clause you can declare a type variable to capture part of the matched type:
type ElementOf<T> = T extends readonly (infer E)[] ? E : never;
type FirstArg<F> = F extends (first: infer A, ...rest: any[]) => any ? A : never;
type Unwrap<T> = T extends PromiseLike<infer V> ? Unwrap<V> : T; // recursive
Many built-ins are written like this: ReturnType, Parameters, Awaited, InstanceType.
infer ... extends (TypeScript 4.7+)
You can constrain what infer captures, which is handy with template literals:
type NumericString<T> = T extends `${infer N extends number}` ? N : never;
type E = NumericString<"42">; // 42
type F = NumericString<"forty-two">; // never
A practical use: types that depend on an argument
type Endpoints = {
"/users": { id: number; name: string }[];
"/status": { ok: boolean };
};
type ResponseFor<P extends string> = P extends keyof Endpoints ? Endpoints[P] : unknown;
async function get<P extends keyof Endpoints>(path: P): Promise<ResponseFor<P>> { ... }
const users = await get("/users"); // { id: number; name: string }[]
The caller gets a precise type per endpoint from a single function.
Why conditional types fight you inside generic functions
Inside get, P is not known yet, so ResponseFor<P> cannot be resolved; it is deferred. TypeScript then cannot prove that Endpoints[P] is assignable to ResponseFor<P>, and you need a cast:
return fakeServer[path] as ResponseFor<P>;
The same happens with return types like T extends string ? "text" : "number": checking typeof value === "string" narrows value, but does not narrow the type parameter T itself. Common ways to handle it:
- Accept a small, well-commented cast inside the implementation, and test it.
- Use function overloads for the public signature and a simpler implementation signature.
- Restructure with an indexed access type (
Endpoints[P]) instead of a conditional when possible; indexed access types are easier for the checker to relate.
Check yourself
- What is
Exclude<string | number | boolean, number>and why? - Why is
IsString<never>equal tonever? - Write a type
Flatten<T>that turnsT[]intoTand leaves other types alone.