Recursive conditionals
Concept and syntax
A recursive conditional may reduce a nested input to its base type. Here readonly array layers are peeled until a non-array is reached. A base case and progress are essential; arbitrary recursive or self-referential input can hit compiler limits.
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 Leaf<T>=T extends readonly (infer U)[]?Leaf<U>:T; type L=Leaf<readonly (number[][])[]>;const n:L=7; console.log(n);Expected output:
7Common mistake
Intentionally invalid; compile separately and do not execute.
type Leaf<T>=T extends readonly (infer U)[]?Leaf<U>:T; type L=Leaf<readonly (number[][])[]>;const n:L=[7];Expected diagnostic: TS2322. All array layers were removed, leaving number.
Practice and recap
Try a union with a non-array branch.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Recursive conditionals — knowledge check
Check the type transformation, trace output, diagnose a rejected example, and apply the concept to a new case.
Which statement about Recursive conditionals is accurate?
What is the complete stdout, represented as a JSON string (including newline characters)?
type Leaf<T>=T extends readonly (infer U)[]?Leaf<U>:T; type L=Leaf<readonly (number[][])[]>;const n:L=7; console.log(n);Which diagnostic and explanation match the rejected example under the lesson settings?
type Leaf<T>=T extends readonly (infer U)[]?Leaf<U>:T; type L=Leaf<readonly (number[][])[]>;const n:L=[7];What is Leaf<readonly string[][]>?