Constrained conditional branches
Concept and syntax
Moving a constraint into a conditional lets unsupported inputs select a fallback. The true branch knows the tested structural requirement and can index its property. An outer generic constraint would instead reject unsupported arguments.
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 Label<T> = T extends {label:unknown} ? T["label"] : false;const a:Label<{label:string}>="tea"; const b:Label<number>=false; console.log(a,b);Expected output:
tea falseCommon mistake
Intentionally invalid; compile separately and do not execute.
type Label<T> = T extends {label:unknown} ? T["label"] : false;const a:Label<number>="tea";Expected diagnostic: TS2322. number does not satisfy the label shape, so the result is false.
Practice and recap
Change the fallback to null and test a missing property.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Constrained conditional branches — knowledge check
Check the type transformation, trace output, diagnose a rejected example, and apply the concept to a new case.
Which statement about Constrained conditional branches is accurate?
What is the complete stdout, represented as a JSON string (including newline characters)?
type Label<T> = T extends {label:unknown} ? T["label"] : false;const a:Label<{label:string}>="tea"; const b:Label<number>=false; console.log(a,b);Which diagnostic and explanation match the rejected example under the lesson settings?
type Label<T> = T extends {label:unknown} ? T["label"] : false;const a:Label<number>="tea";What does Label<{label:boolean}> evaluate to?