title: Extending React components in TypeScript
body: <p>I'm using React.js with TypeScript. Is there any way to create React components that inherit from other components but have some additional props/states?</p>
  
  <p>What I'm trying to achieve is something like this:</p>
  
  <pre><code>interface BaseStates {
      a: number;
  }
  
  class GenericBase&lt;S extends BaseStates&gt; extends React.Component&lt;void, S&gt; {
      protected getBaseInitialState(): BaseStates {
          return { a: 3 };
      }
  }
  
  class Base extends GenericBase&lt;BaseStates&gt; {
      getInitialState(): BaseStates {
          return super.getBaseInitialState();
      }
  }
  
  interface DerivedStates extends BaseStates {
      b: number;
  }
  
  class Derived extends GenericBase&lt;DerivedStates&gt; {
      getInitialState(): DerivedStates {
          var initialStates = super.getBaseInitialState() as DerivedStates; // unsafe??
          initialStates.b = 4;
          return initialStates
      }
  }
  </code></pre>
  
  <p>However, this will fail if I call <code>this.setState</code> in <code>Derived</code>, I get a TypeScript error (parameter of type <code>DerivedStates</code> is not assignable to type <code>S</code>). I suppose this is not a TypeScript-specific thing, but a general limitation of mixing inheritance with generics (?). Is there any type-safe workaround for this?</p>
  
  <p><strong>UPDATE</strong></p>
  
  <p>The solution I settled on (based on the answer of David Sherret):</p>
  
  <pre><code>interface BaseStates {
      a: number;
  }
  
  class GenericBase&lt;S extends BaseStates&gt; extends React.Component&lt;void, S&gt; {
      constructor() {
          super();
          this.state = this.getInitialState();
      }
  
      getInitialState(): S {
          return { a: 3 } as S;
      }
  
      update() {
          this.setState({ a: 7 } as S);
      }
  }
  
  interface DerivedStates extends BaseStates {
      b: number;
  }
  
  class Derived extends GenericBase&lt;DerivedStates&gt; {
      getInitialState(): DerivedStates {
          var initialStates = super.getInitialState();
          initialStates.b = 4;
          return initialStates;
      }
  
      update() {
          this.setState({ a: 7, b: 4 });
      }
  }
  </code></pre>