Q31: What is the `infer` keyword and how is it used in conditional types?
The infer keyword introduces a variable-like type declaration within the conditional check clause of a conditional type, allowing TypeScript to extract and deduce subtype components automatically.
Extracting Promise Inner Value with infer
type UnpackPromise<T> = T extends Promise<infer U> ? U : T;
type ResolvedString = UnpackPromise<Promise<string>>; // string
type PlainNumber = UnpackPromise<number>; // number💡 infer U declares a type variable U captured if T matches Promise<U>.
Key Takeaways
inferextracts sub-types dynamically inside conditional type pattern checks.