The infer Keyword
Extracting inner types from inside complex types.
Surgical Type Extraction
The infer keyword allows you to reach inside a complex type and extract a specific inner type into a new, temporary type variable.
It is most commonly used to unwrap types, like getting the item type out of an Array, or getting the return type out of a Function.
Dealing with Black Boxes
Sometimes a third-party library gives you a function fetchUser(): Promise<User>, but they forgot to export the User type itself!
Instead of redefining User manually, you can use infer to "reach into" the Promise and extract the User type dynamically.
Syntax
typescript
// "If T is an Array of some type R, give me R. Otherwise, give me T."
type UnpackArray<T> = T extends Array<infer R> ? R : T;
type A = UnpackArray<string[]>; // string
type B = UnpackArray<number>; // number
// "If T is a function returning some type R, give me R."
type GetReturn<T> = T extends (...args: any[]) => infer R ? R : never;
type C = GetReturn<() => boolean>; // boolean
Try it
Watch how the infer R keyword physically reaches into the Array<string> wrapper and yanks out the inner string type.
string into R!Check yourself
Pick an answer to lock it in, then read why. Getting one wrong is part of how it sticks.
Remember this
infer Rdeclares a temporary type variableRto capture an inner type.- It can ONLY be used inside the
extendsclause of a conditional type. - It is incredibly useful for unwrapping Arrays, Promises, and Functions.
- If the extraction succeeds, you can return
Rin the true branch of the conditional.
Done with this concept?
Mark it complete to track your progress. No login needed.