Conditional Types
Inferred Array Item
The infer keyword captures part of a type inside a conditional type.
Inferred Array Item
array_item.ts
type ItemOf<T> = T extends Array<infer U> ? U : T;
function firstItem<T>(input: T | T[]): ItemOf<T[]> {
const list: T[] = Array.isArray(input) ? input : [input];
return list[0] as ItemOf<T[]>;
}
const useList: boolean = ;
const input: string | string[] = useList ? ["red", "blue"] : "green";
const item: string = firstItem(input);
console.log(`item=${item}`);
type ItemOf<T> = T extends Array<infer U> ? U : T;
function firstItem<T>(input: T | T[]): ItemOf<T[]> {
const list: T[] = Array.isArray(input) ? input : [input];
return list[0] as ItemOf<T[]>;
}
const useList: boolean = ;
const input: string | string[] = useList ? ["red", "blue"] : "green";
const item: string = firstItem(input);
console.log(`item=${item}`);
infer
`T extends Array<infer U> ? U : T` asks TypeScript to infer the item type when `T` is an array.