Using infer in Conditional Types for Extraction
What You'll Learn
You'll learn the fundamental pattern of combining infer with conditional types to extract specific type components, creating powerful type-level transformations.
The Extraction Pattern
While you've seen infer extract individual type components, the real power emerges when you structure conditional types specifically to pull out nested information. Think of it like a smart search function that not only finds what you're looking for but also pulls it out and hands it to you.
The core pattern looks like this:
type ExtractSomething<T> = T extends SomePattern<infer U> ? U : never;
This reads as: "If T matches SomePattern, extract the inner type as U and return it; otherwise, return never."
Building Practical Extractors
Let's see how this pattern creates useful utilities:
// Extract the element type from arrays
type ElementType<T> = T extends (infer U)[] ? U : never;
type NumType = ElementType<number[]>; // number
type StrType = ElementType<string[]>; // string
type NotArray = ElementType<boolean>; // never
The extraction happens because infer U captures whatever type fills that position in the pattern.
Extracting from Promise Chains
// Extract what a Promise resolves to
type UnwrapPromise<T> = T extends Promise<infer U> ? U : T;
type Result = UnwrapPromise<Promise<string>>; // string
type AlreadyUnwrapped = UnwrapPromise<number>; // number
Notice how extraction includes a fallback: if the pattern doesn't match, we return the original type (or never).
Extracting Function Components
// Extract just the first parameter
type FirstParam<T> = T extends (first: infer F, ...rest: any[]) => any
? F
: never;
type FnParam = FirstParam<(name: string, age: number) => void>; // string
The extraction pattern positions infer F exactly where the first parameter sits, capturing its type.
The Extraction Philosophy
The key insight is that infer acts as a placeholder that captures whatever type appears in that structural position. You're designing a type-level pattern-matching function where infer marks the "capture groups" you want to extract.
// Extract the middle type from a three-element tuple
type Middle<T> = T extends [any, infer M, any] ? M : never;
type MiddleValue = Middle<[1, "hello", true]>; // "hello"
This pattern is foundational for building sophisticated type transformations—you're essentially asking TypeScript: "Does this type look like X? If so, give me the Y part."
Key Takeaway: The infer extraction pattern uses conditional types to structurally match against a type shape and capture specific components, creating reusable type-level extraction utilities that power advanced type transformations.