Inheriting Multiple Classes in TypeScript

In what ways can you get around the problem only in order to allow the extension of no more than one other class.

class Bar { doBarThings() { //... } } class Bazz { doBazzThings() { //... } } class Foo extends Bar, Bazz { doBarThings() { super.doBarThings(); //... } } 

This is currently not possible, TypeScript will throw an error. This problem can be solved in other languages ​​using interfaces, but the solution to the problem with them is not possible in TypeScript.

Suggestions are welcome!

+6
source share
2 answers

This is possible with the interfaces:

 interface IBar { doBarThings(); } interface IBazz { doBazzThings(); } class Foo implements IBar, IBazz { doBarThings() {} doBazzThings(){} } 

But if you want to implement this in super / base style, then you will need to do something else, for example:

 class FooBase implements IBar, IBazz{ doBarThings() {} doBazzThings(){} } class Foo extends FooBase { doFooThings(){ super.doBarThings(); super.doBazzThings(); } } 
+3
source

This is my way of extending multiple classes. This allows for pretty nice type safety. I have not yet been able to find any significant flaws in this approach, which works the same as with multiple inheritance.

 // tslint:disable: max-classes-per-file class Base {} type Constructor<I = {}> = new (...args: any[]) => I | {}; interface IBar { doBarThings(): void; } interface IBazz { doBazzThings(): void; } function Bar<T extends Constructor>(constructor: T) { return class extends constructor implements IBar { public doBarThings() { console.log("Do bar!"); } }; } function Bazz<T extends Constructor>(constructor: T) { return class extends constructor implements IBazz { public doBazzThings() { console.log("Do bazz!"); } }; } class Foo extends Bar(Bazz(Base)) implements IBar, IBazz { public doBarThings() { super.doBarThings(); console.log("Override mixin"); } } const foo = new Foo(); foo.doBazzThings(); // Do bazz! foo.doBarThings(); // Do bar! // Override mixin 
0
source

All Articles