Conditional types and infer
7.0.2
Choose a result type based on another type. Use infer to name a type found inside a matching structure.
On this page
Read the item type of an array
The conditional reads like an if statement for types. If T matches a readonly array, infer Item names the type of the elements. Otherwise the result is T.
type ItemOf<T> = T extends readonly (infer Item)[] ? Item : T;
type Name = ItemOf<readonly string[]>; // string
type Existing = ItemOf<number>; // number
Choose how to handle unions
When the checked side is a plain type parameter, the condition runs for each member of the union. Wrap both sides in square brackets when you want to check the union as a whole.
type ToArrays<T> = T extends unknown ? T[] : never;
type ToArray<T> = [T] extends [unknown] ? T[] : never;
type Separate = ToArrays<string | number>; // string[] | number[]
type Mixed = ToArray<string | number>; // (string | number)[]