title: TypeScript Generics: 'type is not assignable to type T'
body: <p>I have made a factory that will create instances of certain classes. I want to use generics to ensure that all of the objects returned are from sub-classes that extend an abstract classes.</p>
  
  <p>I thought that the logic of the <code>createInstance</code> method shown below could be described as 'createInstance() will return a type <code>T</code> that is constrained to be a class that extends Animal.</p>
  
  <p>As you can see, Lion extends Animal, but I still get the compiler warning <code>type Lion is not assignable to type T</code>. </p>
  
  <pre><code>abstract class Animal {
      abstract makeSound(): void;
  }
  
  class Bear extends Animal {
      public makeSound() {
          console.log('growl');
      }
  }
  
  class Lion extends Animal {
      public makeSound() {
          console.log('roar');
      }
  }
  
  function createInstance&lt;T extends Animal&gt;(type: string): T {
      switch(type) {
          case 'bear':
              return new Bear(); // 'type Bear is not assignable to type T'
          case 'lion':
              return new Lion(); // 'type Lion is not assignable to type T'
      }
  }
  
  createInstance().makeSound();
  </code></pre>
  
  <p>I have read at the end of the <a href="https://www.typescriptlang.org/docs/handbook/generics.html" rel="noreferrer">TypeScript Generics</a> docs that:</p>
  
  <blockquote>
    <p>When creating factories in TypeScript using generics, it is necessary
    to refer to class types by their constructor functions. For example,</p>
  
  <pre><code>function create&lt;T&gt;(c: {new(): T; }): T {
      return new c();
  }
  </code></pre>
  </blockquote>
  
  <p>but I don't really want to have to pass in the class constructor into the function if possible and would like to understand why I'm getting the <code>not assignable to type T</code> message in the first place.</p>
  
  <p>Thanks</p>