title: Typescript Parent Class type guard to Child Classes
body: <p>I have a an abstract class <code>FooObject</code>. Only two children ever inherit <code>FooObject</code>, lets call them <code>ThisFooObject</code> and <code>ThatFooObject</code>.</p>
  
  <p>I'm looking for a <strong>performant</strong> way to turn a FooObject into whichever child it is. In this case, that means not using <code>instanceof</code> - which <a href="https://jsperf.com/instanceof-performance/2" rel="nofollow noreferrer">performs</a> at &lt;10% the speed of a boolean lookup.</p>
  
  <p>The way I've investigated is something like this:</p>
  
  <h1>FooObject.ts</h1>
  
  <pre><code>import ThisObject from "./ThisObject";
  import ThatObject from "./ThatObject";
  
  abstract class FooObject {
  
    isThisObject() : this is ThisFooObject {
      // Either check for ThisFooObject properties, or override this
      // in the ThisFooObject class to always return true.
      return duckTypingTest();
    }
  
    // ditto here
    isThatObject() : this is ThatFooObject {}
  }
  </code></pre>
  
  <p>I understand that this is not pretty. It's not a scalable approach if I have more children of FooObject - and it requires the parent to know about the children in a kinda encapsulation breaking way. But in my specific case, I'm willing to put up with this if it avoids me having to do 'instanceof'.</p>
  
  <p>On the bright side, when I have a reference to a FooObject, and I want to something when it's a ThatFooObject, I can do something like:</p>
  
  <pre><code>fooObjects.forEach( foo =&gt; {
    // Foo currently typed as a FooObject
    if(foo.isThatObject()){
      // Foo now typed as a ThatFooObject
      foo.magic+=10
    }
  });
  </code></pre>
  
  <p>This is all works - with one little caveat - I have to <a href="https://stackoverflow.com/questions/37067411/cross-referencing-between-parent-and-child-class">be careful</a> to get the import order correct. IE, in my <code>main.ts</code> entry point, do something like</p>
  
  <pre><code>import 'ThatFooObject';
  import 'FooObject';
  </code></pre>
  
  <p>But other than that, I'm fairly well pleased with this pattern. The issue comes when I try this with <strong>more than one</strong> child. I start to get issues with circular dependencies throwing things off, and errors like <code>class extends value undefined is not a constructor or null</code>. </p>
  
  <p>I can't figure out how to make this work. Am I just barking up the wrong tree, and I should do this a much simpler way?</p>