title: When to use Discriminated Unions vs Classes implementing an interface
body: <p>I have code like this:</p>
  <pre><code>interface Node{
      value: number;
  }
  
  class Parent implements Node{
      children: Node[] = [];
      value: number = 0;
  }
  
  
  class Leaf implements Node{
      value: number = 0;
  }
  
  
  function test(a:Node) : void {
    if(a instanceof Leaf)
      console.log(&quot;Leaf&quot;)
    else 
      console.log(&quot;Parent&quot;)
  }
  </code></pre>
  <p>Looking at <a href="https://www.typescriptlang.org/docs/handbook/typescript-in-5-minutes-func.html#discriminated-unions" rel="nofollow noreferrer">https://www.typescriptlang.org/docs/handbook/typescript-in-5-minutes-func.html#discriminated-unions</a>, it seems like a different way of achieving this would be</p>
  <pre><code>type Parent = {kind: &quot;Parent&quot;, value:number, children:(A|B)[]}
  type Leaf = {kind: &quot;Leaf&quot;, value:number}
  
  type Node = Parent | Leaf
  
  function test(a:Node) :void {
    if(a.kind === &quot;Leaf&quot;)
      console.log(&quot;yes&quot;)
    else 
      console.log(&quot;no&quot;)
  }
  </code></pre>
  <p>Now, I'm confused as to what to use. All other languages I have used until now only had one of those options - here is typescript with both. Besides approach 1 having a constructor, while approach 2 is completely transpiled away, what are the real differences here? Which method is preferably seen in codebase?</p>
  <p>The functionality, as you can see, is so that we can easily traverse a tree. Of course I could also just have only one type/class and set the children to [] there, but then the question of type vs class is repeated. And I was told that having different classes was more performance friendly.</p>