Sub topic 1
TypeScript `infer` and Recursive Types: Extracting and Transforming Types
Prerequisites
This chapter assumes you know TypeScript generics, unions, tuples, function signatures, mapped types, and basic template literal types.
Conditional types: choosing a type with `extends`
A conditional type selects one of two types:
type IsString<T> = T extends string ? true : false;
type A = IsString<"hello">; // true
type B = IsString<42>; // falseTypeScript checks whether T is assignable to string. If it is, the result is the type before :, otherwise it is the type after :.
The checked type should usually be a type parameter. This enables distribution over unions.
How conditional types distribute over unions
When a naked type parameter appears on the left side of extends, TypeScript evaluates each union member separately:
type ToArray<T> = T extends unknown ? T[] : never;
type Result = ToArray<string | number>;
// string[] | number[]This differs from wrapping the parameter:
type ToArrayTogether<T> = [T] extends [unknown] ? T[] : never;
type Result = ToArrayTogether<string | number>;
// (string | number)[]Use the wrapped form when you want to test the union as one value.
Capturing a type with `infer`
The infer keyword declares a temporary type variable inside a matching pattern. TypeScript fills in that variable when the input matches.
type ElementType<T> = T extends (infer U)[] ? U : never;
type Names = ElementType<string[]>; // string
type NotAnArray = ElementType<number>; // neverThe pattern asks, “Can T be treated as an array?” If so, infer U captures the element type.
Extracting common function and container types
infer can appear in function, array, tuple, and Promise patterns:
type MyReturnType<T> =
T extends (...args: any[]) => infer R ? R : never;
type MyParameters<T> =
T extends (...args: infer P) => any ? P : never;
type UnwrapPromise<T> =
T extends PromiseLike<infer U> ? U : never;
function makeUser(name: string, age: number) {
return { name, age };
}
type User = MyReturnType<typeof makeUser>;
// { name: string; age: number }
type Args = MyParameters<typeof makeUser>;
// [name: string, age: number]
type Value = UnwrapPromise<Promise<number>>; // numberThe same matching idea powers built-in utilities such as ReturnType, Parameters, and Awaited.
Exercise
What is the result of ToArray<boolean | Date>?
Show answer
boolean[] | Date[], because the distributive conditional evaluates each union member separately.