Nested and constrained infer
Concept and syntax
Constrained infer matches and binds only candidates satisfying its constraint. Nested patterns can extract deeply placed components without multiple separate aliases. This example rejects a nonnumeric inner value rather than converting it.
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 Count<T>=T extends {box:{value:infer N extends number}}?N:never;const n:Count<{box:{value:7}}>=7; console.log(n);Expected output:
7Common mistake
Intentionally invalid; compile separately and do not execute.
type Count<T>=T extends {box:{value:infer N extends number}}?N:never;const n:Count<{box:{value:"7"}}>=7;Expected diagnostic: TS2322. The inferred string fails the number constraint, yielding never.
Practice and recap
Use a constraint of string and compare literal preservation.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Nested and constrained infer — knowledge check
Check the type transformation, trace output, diagnose a rejected example, and apply the concept to a new case.
Which statement about Nested and constrained infer is accurate?
What is the complete stdout, represented as a JSON string (including newline characters)?
type Count<T>=T extends {box:{value:infer N extends number}}?N:never;const n:Count<{box:{value:7}}>=7; console.log(n);Which diagnostic and explanation match the rejected example under the lesson settings?
type Count<T>=T extends {box:{value:infer N extends number}}?N:never;const n:Count<{box:{value:"7"}}>=7;What does Count<{box:{value:3}}> select?