Multiple infer in One Conditional
What you'll learn: How to use multiple infer declarations within a single conditional type to extract several related pieces of type information simultaneously.
When working with conditional types, you often need to extract more than one piece of information from a complex type. TypeScript allows you to use multiple infer keywords in a single conditional type expression, each capturing a different part of the type structure.
The Core Pattern
Just as you can use one infer to extract a single piece (like a function's return type), you can use multiple infer declarations to extract several pieces at once. Each infer keyword introduces a new type variable that captures a different part of the pattern you're matching.
The syntax looks like this:
type ExtractBoth<T> = T extends SomePattern<infer A, infer B>
? [A, B]
: never;
Extracting Multiple Function Parts
Consider extracting both a function's parameter types and return type simultaneously:
type FunctionParts<T> = T extends (arg: infer P) => infer R
? { parameter: P; returnType: R }
: never;
type Example = FunctionParts<(name: string) => number>;
// Result: { parameter: string; returnType: number }
Here, infer P captures the parameter type while infer R captures the return type in the same conditional.
Multiple Parameters
You can extract several function parameters individually:
type FirstTwo<T> = T extends (first: infer A, second: infer B, ...rest: any[]) => any
? [A, B]
: never;
type Params = FirstTwo<(x: string, y: number, z: boolean) => void>;
// Result: [string, number]
Nested Structure Extraction
Extract multiple levels from nested structures:
type UnwrapNested<T> = T extends Promise<infer Inner>
? Inner extends Array<infer Element>
? { inner: Inner; element: Element }
: never
: never;
type Result = UnwrapNested<Promise<string[]>>;
// Result: { inner: string[]; element: string }
Practical Use: Tuple Decomposition
Extract the first and last elements from a tuple:
type FirstAndLast<T extends any[]> = T extends [infer First, ...any[], infer Last]
? [First, Last]
: never;
type Ends = FirstAndLast<[1, 2, 3, 4, 5]>;
// Result: [1, 5]
The middle ...any[] allows any elements in between, while both infer declarations capture the edges.
Why This Matters
Multiple infer declarations let you decompose complex types into their constituent parts in a single pass, avoiding the need to chain multiple conditional types together. This makes your type transformations more concise and often more readable.
Key Takeaway: Multiple infer keywords in one conditional type let you simultaneously extract several related type components, enabling powerful single-pass type decomposition and transformation patterns.