Skip to content

Instantly share code, notes, and snippets.

@tamert
Created September 5, 2021 14:19
Show Gist options
  • Save tamert/81fe49f1bece103c331b91bb86d38bb9 to your computer and use it in GitHub Desktop.
Save tamert/81fe49f1bece103c331b91bb86d38bb9 to your computer and use it in GitHub Desktop.
Typescript Multiple Inheritance
function applyMixins(derivedCtor: any, baseCtors: any[]) {
baseCtors.forEach(baseCtor => {
Object.getOwnPropertyNames(baseCtor.prototype).forEach(name => {
derivedCtor.prototype[name] = baseCtor.prototype[name];
});
});
}
class Animal {
name: string;
constructor(theName: string) {
this.name = theName;
}
move(distanceInMeters: number = 0) {
console.log(`${this.name} moved ${distanceInMeters}m.`);
}
}
class Snake {
name: string;
constructor(theName: string) {
this.name = theName;
}
move(distanceInMeters = 5) {
console.log("Slithering...");
}
}
class Horse {
name: string;
constructor(name: string) {
this.name = name
}
move(distanceInMeters = 45) {
console.log("Galloping...");
}
}
applyMixins(Horse, [Animal, Snake]);
let tom = new Horse("Tommy the Palomino");
tom.move(34);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment