title: How to extract type of recursively nested children properties in TypeScript?
body: <p>I'm trying to model a recursive tree relationship of nodes of two types: text nodes and element nodes (like the DOM). Text nodes are leaves in the tree, and element nodes can contain other element nodes or text nodes.</p>
  <pre><code>type Text = {
      text: string
  }
  
  type Element = {
      children: Node[]
  }
  
  type Node = Element | Text
  </code></pre>
  <p>Consider these nodes:</p>
  <pre><code>type A = {
      children: Text[]
  }
  
  type B = {
      children: A[]
  }
  
  type C = {
      children: B[]
  }
  </code></pre>
  <p>Given a specific <code>Node</code>, I'd like to write a utility type that will return the union of its potential descendants (deep).</p>
  <p>Writing the utility for just the children (shallow) is straightforward:</p>
  <pre><code>type ChildOf&lt;N extends Node&gt; = 
      N extends Element
          ? N['children'][number]
          : never
  
  ChildOf&lt;A&gt; // Text
  ChildOf&lt;B&gt; // A
  ChildOf&lt;C&gt; // B
  ChildOf&lt;Text&gt; // never
  </code></pre>
  <p>But how would you write a recursive utility to get all of the deep descendants and not just the shallow children?</p>
  <pre><code>type DescendantOf&lt;N extends Node&gt; = ???
  
  DescendantOf&lt;A&gt; // Text
  DescendantOf&lt;B&gt; // A | Text
  DescendantOf&lt;C&gt; // A | B | Text
  DescendantOf&lt;Text&gt; // never
  </code></pre>