Extract a type with infer
Use infer inside a conditional type to capture part of another type, such as an array's element or a function's first argument. TypeScript 5 and earlier.
You want the element type of an array, or the first parameter of a function, as a named type. infer declares a variable the compiler fills in during the match.
type ElementOf<T> = T extends readonly (infer U)[] ? U : never;
type FirstArg<F> = F extends (first: infer A, ...rest: any[]) => unknown ? A : never;
function greet(name: string, excited: boolean): string {
return excited ? `Hi ${name}!` : `Hi ${name}`;
}
const name: FirstArg<typeof greet> = 'Ada'; // string
const first: ElementOf<string[]> = 'x'; // string
console.log(name, first);Ada xIn T extends readonly (infer U)[], U is not a name you declared elsewhere. The compiler matches T against the pattern and, if it fits, binds U to whatever sat in that position. ElementOf<string[]> is string. The built-in ReturnType and Parameters are written the same way. See inferring within conditional types.
infer can only appear in the extends clause of a conditional type. If the pattern does not match, you get the false branch, here never. When a type parameter shows up in several positions, TypeScript infers a union for covariant positions and an intersection for contravariant ones.