Sub topic 2
Narrowing Inferred Types with `infer extends`
Assume you know TypeScript generics, unions, intersections, tuples, mapped types, function signatures, and basic template literal types. Conditional types choose between two branches:
type IsString<T> = T extends string ? true : false;
type A = IsString<"ok">; // true
type B = IsString<42>; // falseConstraining an Inferred Type
infer introduces a type variable while matching a pattern. Add extends when the inferred value must satisfy a constraint:
type FirstString<T> =
T extends [infer S extends string, ...unknown[]] ? S : never;
type A = FirstString<["ready", 123]>; // "ready"
type B = FirstString<[123, "ready"]>; // neverThe first tuple element is inferred as S. The match succeeds only when S extends string. Without the constraint, the first example would also match numbers.
Multiple Candidates: Unions and Intersections
When a type variable is inferred from multiple positions, TypeScript combines candidates according to their positions.
- Covariant positions, such as array elements and return types, usually produce a union.
- Contravariant positions, such as function parameters, usually produce an intersection.
This pattern converts a union into an intersection:
type UnionToIntersection<U> =
(U extends unknown ? (arg: U) => void : never) extends
(arg: infer I) => void
? I
: never;
type Merged = UnionToIntersection<{ a: 1 } | { b: 2 }>;
// { a: 1 } & { b: 2 }The distributive conditional creates a union of functions. Inferring from their parameter position combines those candidates into an intersection.
Recursive Type Aliases
A recursive type alias refers to itself. It needs a smaller recursive input and a base case that stops recursion.
type UnwrapPromise<T> =
T extends PromiseLike<infer U>
? UnwrapPromise<U>
: T;
type Result = UnwrapPromise<Promise<Promise<number>>>; // number
type Text = UnwrapPromise<string>; // stringThe conditional removes one Promise layer, then calls itself with the inner type. A non-Promise reaches the base case and returns unchanged.
Exercise
What is UnwrapPromise<Promise<Promise<boolean>>>?
Show answer
boolean, because each matching branch removes one Promise layer.