Challenge 3: Count Tree Depth (Depth-Limited Repeat) — Possible Solution ==================================================================== This solution takes the simpler variant offered in the challenge: a depth-limited Repeat, using the counting-tuple trick from the chapter. type Repeat = Acc["length"] extends N ? Acc : Repeat; // --- Usage --- type ThreeStrings = Repeat; // [string, string, string] type FiveNumbers = Repeat; // [number, number, number, number, number] type ZeroItems = Repeat; // [] — base case hit immediately // Step-by-step for Repeat: // // Repeat // -> Acc["length"] (0) extends 3? no // -> recurse: Repeat // -> Acc["length"] (1) extends 3? no // -> recurse: Repeat // -> Acc["length"] (2) extends 3? no // -> recurse: Repeat // -> Acc["length"] (3) extends 3? YES — return Acc // --- Bonus: TreeDepth for an actual TreeNode value's TYPE shape --- // (Harder variant — measuring depth from a tree's nested `children` shape // rather than counting toward a fixed N.) interface TreeNode { value: T; children: TreeNode[]; } // This version caps out at a fixed maximum depth (10) to avoid the // "excessively deep" error on a genuinely unbounded TreeNode type, // since a TreeNode's `children` array doesn't carry compile-time length // information the way a tuple's `Acc["length"]` does. type TreeDepth = Depth["length"] extends 10 ? Depth["length"] : T extends { children: infer C } ? C extends TreeNode[] ? TreeDepth : Depth["length"] : Depth["length"]; WHY THIS WORKS -------------- - Acc["length"] reads a tuple type's length as a numeric literal — since [...Acc, T] appends exactly one element per recursive call, the length grows by exactly 1 each time, giving the recursion a way to "count up" toward N. - Acc["length"] extends N is the explicit stopping condition — the moment the accumulated tuple's length matches N, the recursion stops and returns the accumulated tuple instead of calling itself again. - The bonus TreeDepth variant caps recursion at a fixed maximum (10) because, unlike a tuple that structurally encodes its own length, TreeNode's `children` array has no compile-time-visible length — a hard cap is the standard defensive technique to avoid the "excessively deep and possibly infinite" error on a structure the compiler can't otherwise prove terminates.