title: TypeScript: class composition
body: <p>Based on this awesome <a href="https://youtu.be/wfMtDGfHWpA" rel="noreferrer" title="Composition over Inheritance">Composition over Inheritance</a> video by MPJ, I've been trying to formulate composition in TypeScript. I want to compose <strong>classes</strong>, not objects or factory functions. Here is my effort so far (with a little help from <em>lodash</em>):</p>
  <pre><code>class Barker {
    constructor(private state) {}
  
    bark() {
      console.log(`Woof, I am ${this.state.name}`);
    }
  }
  
  class Driver {
    constructor(private state) {}
  
    drive() {
      this.state.position = this.state.position + this.state.speed;
    }
  }
  
  class Killer {
    constructor(private state) {}
  
    kill() {
      console.log(`Burn the ${this.state.prey}`);
    }
  }
  
  class MurderRobotDog {
    constructor(private state) {
      return _.assignIn(
        {},
        new Killer(state),
        new Driver(state),
        new Barker(state)
      );
    }
  }
  
  const metalhead = new MurderRobotDog({ 
    name: 'Metalhead', 
    position: 0, 
    speed: 100, 
    prey: 'witch' 
  });
  
  metalhead.bark(); // expected: &quot;Woof, I am Metalhead&quot;
  metalhead.kill(); // expected: &quot;Burn the witch&quot;
  </code></pre>
  <p>This resulting in:</p>
  <blockquote>
  <p>TS2339: Property 'bark' does not exist on type 'MurderRobotDog'</p>
  <p>TS2339: Property 'kill' does not exist on type 'MurderRobotDog'</p>
  </blockquote>
  <p>What's the right way of doing class composition in TypeScript?</p>