Nested and deferred conditionals
Concept and syntax
Nested conditionals express ordered type tests. When a generic parameter is still unresolved, the compiler may defer the choice until instantiation. A generic implementation cannot assume a branch just because a runtime test resembles the type test.
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 Kind<T>=T extends string?"text":T extends number?"count":"other";const k:Kind<number>="count"; console.log(k);Expected output:
countCommon mistake
Intentionally invalid; compile separately and do not execute.
type Kind<T>=T extends string?"text":T extends number?"count":"other";function guess<T>(x:T):Kind<T>{return "text";}Expected diagnostic: TS2322. An arbitrary T may select a different branch; returning text is not justified.
Practice and recap
Add a boolean branch before the fallback.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Nested and deferred conditionals — 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 deferred conditionals is accurate?
What is the complete stdout, represented as a JSON string (including newline characters)?
type Kind<T>=T extends string?"text":T extends number?"count":"other";const k:Kind<number>="count"; console.log(k);Which diagnostic and explanation match the rejected example under the lesson settings?
type Kind<T>=T extends string?"text":T extends number?"count":"other";function guess<T>(x:T):Kind<T>{return "text";}What does Kind<boolean> select?