title: Can I check a type against a union type in typescript?
body: <p>Is there a way to do an "instanceof"-like query on an object against a union type that's built into the language?</p>
  
  <p>I have a type alias with a union type as follows:</p>
  
  <pre><code>type MyType = Foo | Bar | Thing;
  </code></pre>
  
  <p>Each of <code>Foo</code>, <code>Bar</code> and <code>Thing</code> inherit from <code>Base</code></p>
  
  <pre><code>class Base { /* ... */ }
  class Foo extends Base { /* ... */ }
  class Bar extends Base { /* ... */ }
  class Thing extends Base { /* ... */ }
  </code></pre>
  
  <p>Some method returns a <code>Base</code>.</p>
  
  <pre><code>function getBase(): Base { /* ... */ return base; }
  </code></pre>
  
  <p>Ideally, I would like to create another method that can return a <code>MyType</code> after calling <code>getBase()</code></p>
  
  <pre><code>function getMyType(): MyType { 
      var item = getBase();
      if (item instanceof MyType)
          return item;
      else
          return null;
  }
  </code></pre>
  
  <p>If <code>MyType</code> were not a type alias, the above code would work.  However, since it is a type alias, it doesn't seem to work.  So to re-iterate my question, is something of this nature built into the language?</p>
  
  <p>Clearly, what I want can be accomplished by checking the instanceof query against each individual class:</p>
  
  <pre><code>function getMyType(): MyType { 
      var item = getBase();
      if (item instanceof Foo || item instanceof Bar || item instanceof Thing)
          return item;
      else
          return null;
  }
  </code></pre>
  
  <p>But this is hardly ideal; if some future developer wanted to create <code>OtherThing</code> and extend <code>MyType</code> to also include this new class, then hopefully  remembered to update <code>getMyType()</code>.</p>
  
  <p><strong>Is there a feature built into the language to address this, or is there potentially a better way of doing this?</strong></p>