title: Union Types Inside Union Types
body: <p>I'm confused as why this is a type error:</p>
  <pre><code>type A = A1 | A2;
  
  type A1 = {
    attr: B1;
  }
  
  type A2 = {
    attr: B2
  };
  
  type B = B1 | B2;
  
  type B1 = {
    attr: &quot;B1&quot;
  };
  
  type B2 = {
    attr: &quot;B2&quot;
  };
  
  
  function b(): B {
    return {
      attr: &quot;B1&quot;
    };
  }
  
  function a(): A {
    return {
      attr: b()
    }
  }
  </code></pre>
  <p>This yields the following error:</p>
  <pre><code>Type '{ attr: B; }' is not assignable to type 'A'.
    Type '{ attr: B; }' is not assignable to type 'A2'.
      Types of property 'attr' are incompatible.
        Type 'B' is not assignable to type 'B2'.
          Type 'B1' is not assignable to type 'B2'.
            Types of property 'attr' are incompatible.
              Type '&quot;B1&quot;' is not assignable to type '&quot;B2&quot;'.ts(2322)
  </code></pre>
  <p>As <code>b</code> returns either <code>B1</code> or <code>B2</code> it should adhere to <code>A</code>'s <code>attr</code> type.</p>
  <p>So I don't really understand what's happening here, as it seems to me that there's no type violation.</p>
  <p>EDIT:</p>
  <p>I found a &quot;solution&quot; but it is rather verbose, so I'm still looking for a cleaner way to make the compiler happy.</p>
  <pre><code>function isB1(b: B): b is B1 {
    return b.attr === &quot;B1&quot;;
  }
  
  function isB2(b: B): b is B2 {
    return b.attr === &quot;B2&quot;;
  }
  
  function b(): B {
    return {
      attr: &quot;B1&quot;,
    };
  }
  
  function a(): A {
    const B = b();
    if(isB1(B)) {
      return {
        attr: B,
      };
    }
  
    return {
      attr: B
    };
  }
  </code></pre>