Home TypeScript: Class Composition
Reply: 0

TypeScript: Class Composition

user10249
1#
user10249 Published in September 21, 2018, 8:04 am

Based on this awesome Composition over Inheritance video by MPJ, I've been trying to formulate composition in TypeScript. I want to compose classes, not objects or factory functions. Here is my effort so far (with a little help from lodash):

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: "Woof, I am Metalhead"
metalhead.kill(); // expected: "Burn the witch"

This resulting in:

TS2339: Property 'bark' does not exist on type 'MurderRobotDog'

TS2339: Property 'kill' does not exist on type 'MurderRobotDog'

What's the right way of doing class composition in TypeScript?

share|improve this question
  • 1
    I have no idea what _.assignIn is, but this looks much more like mixins than composition. And no, you cannot easily mix multiple classes – Bergi Feb 12 at 23:20
  • @Bergi lodash.com/docs/4.17.5#assignIn. And yes, my effort goes around this answer over here: stackoverflow.com/a/39243098/2013891 - which suggests we should probably always prefer a mixin over member composition in prototypical language. ¯_(ツ)_/¯ – Glenn Mohammad Feb 12 at 23:36
  • MPJ got composition completely wrong, and actual composition never once made an appearance in his video. What you're looking for is called multiple inheritance or mixins. reddit.com/r/programming/comments/5dxq6i/… – Jeff M Feb 13 at 15:06
  • @GlennMohammad ... but do you also know why a MurderRobotDog instance does not feature any of the expected (prototypal) methods? And / or did you already read the JavaScript code which your TS was transpiled to? – Peter Seliger Feb 14 at 17:03
  • @JeffM Thanks for the great pointer! The thread really opens up my mind about what actual composition is. ❤︎ I always thought mixin is a form of composition. – Glenn Mohammad Feb 16 at 18:42

1 Answer 1

active oldest votes
up vote 1 down vote
You need to login account before you can post.

About| Privacy statement| Terms of Service| Advertising| Contact us| Help| Sitemap|
Processed in 0.324831 second(s) , Gzip On .

© 2016 Powered by mzan.com design MATCHINFO