The infer Keyword
The infer Keyword — the core idea
Within a conditional type, infer introduces a temporary type variable to capture part of a matched structure. You can extract a function return type, an array element type, or the resolved value inside a Promise.
What you’ll learn
- Explain the infer keyword with a concrete use case.
- Run the example and account for every line of its output.
- Recognize the difference between compile-time checking and runtime behavior.
Understand the rules and when to use them
Reading the code: The conditional pattern matches an array type and captures its element as Item. With the array of point objects, Point resolves to {x:number;y:number}. No special runtime extraction happens.
Keep the boundary clear: infer can only introduce a type variable inside a conditional-type extends pattern; it is not JavaScript destructuring.
See the idea as a flow
Run the complete TypeScript example
Save the code as infer-keyword.ts. The result below was captured after compiling this exact example with strict TypeScript checking and executing the emitted JavaScript in Node.js.
TypeScript code
type ElementOf<T> = T extends readonly (infer Item)[] ? Item : never;
type Point = ElementOf<{ x: number; y: number }[]>;
const first: Point = { x: 2, y: 5 };
console.log(`${first.x},${first.y}`);Verified output
2,5Build: npx tsc --strict --target es2022 --module commonjs --lib es2022,dom,esnext.disposable infer-keyword.ts; run: node infer-keyword.js. The exact filename may be changed freely. When a multi-file project exists, prefer its tsconfig.json and build scripts.
Trace the example line by line
The conditional pattern matches an array type and captures its element as Item. With the array of point objects, Point resolves to {x:number;y:number}. No special runtime extraction happens.
The output shown above comes from the initialized values in this program. Replacing a type annotation alone does not transform a JavaScript value.
Avoid this common mistake
infer can only introduce a type variable inside a conditional-type extends pattern; it is not JavaScript destructuring.
Check both the TypeScript diagnostic and the emitted JavaScript behavior. A program can compile correctly and still need runtime validation or error handling.
Practice independently
Use infer to extract the return type of a zero-argument function and assign a matching value.
Before running your change, write down the type you expect TypeScript to infer and the output you expect JavaScript to print. Then check both predictions.
Check your understanding
What to remember
Within a conditional type, infer introduces a temporary type variable to capture part of a matched structure.
Try the practice change and re-run the exact program to test your understanding.
Reaching the recap and completing the quizzes are separate milestones.