Conditional type branches
Concept and syntax
A conditional type selects a branch by assignability: T extends U ? X : Y. It operates on types, not runtime conditions. Here the type of the payload follows the kind argument.
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 Payload<T> = T extends "count" ? number : string;const value:Payload<"count"> = 4; console.log(value);Expected output:
4Common mistake
Intentionally invalid; compile separately and do not execute.
type Payload<T> = T extends "count" ? number : string;const value:Payload<"count"> = "four";Expected diagnostic: TS2322. The count branch requires number, not string.
Practice and recap
Add a boolean branch for "active".
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Conditional type branches — knowledge check
Check the type transformation, trace output, diagnose a rejected example, and apply the concept to a new case.
Which statement about Conditional type branches is accurate?
What is the complete stdout, represented as a JSON string (including newline characters)?
type Payload<T> = T extends "count" ? number : string;const value:Payload<"count"> = 4; console.log(value);Which diagnostic and explanation match the rejected example under the lesson settings?
type Payload<T> = T extends "count" ? number : string;const value:Payload<"count"> = "four";If Payload<"label"> is used, which type is selected?