Infer binding
Concept and syntax
Within a conditional extends pattern, infer introduces a type variable bound to the matching component. It is available in the true branch; the fallback handles shapes that do not match. No runtime property lookup occurs.
Working example
Save each snippet separately as main.ts in a fresh directory with TypeScript 5.8.3. Compile with tsc --strict --target ES2022 --module commonjs --moduleDetection force --skipLibCheck --noEmitOnError main.ts and run accepted snippets with node main.js. Type aliases are erased; assignments and diagnostic checks demonstrate the type relations, not the printed output alone.
type Inner<T>=T extends {data:infer U}?U:never;const n:Inner<{data:number}>=5; console.log(n);Expected output:
5Common mistake
Intentionally invalid; compile separately and do not execute.
type Inner<T>=T extends {data:infer U}?U:never;const n:Inner<{data:number}>="five";Expected diagnostic: TS2322. U is inferred as number from the data field.
Practice and recap
Extract data from a union of two wrapper types.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Infer binding — knowledge check
Check the type transformation, trace output, diagnose a rejected example, and apply the concept to a new case.
Which statement about Infer binding is accurate?
What is the complete stdout, represented as a JSON string (including newline characters)?
type Inner<T>=T extends {data:infer U}?U:never;const n:Inner<{data:number}>=5; console.log(n);Which diagnostic and explanation match the rejected example under the lesson settings?
type Inner<T>=T extends {data:infer U}?U:never;const n:Inner<{data:number}>="five";What does Inner<{data:false}> evaluate to?