nourikhalass
nourikhalass

Reputation: 360

Multiple Class Inheritance In TypeScript

What are ways to get around the problem of only being allowed to extend at most one other class.

class Bar {

  doBarThings() {
    //...
  }

}

class Bazz {

  doBazzThings() {
    //...
  }

}

class Foo extends Bar, Bazz {

  doBarThings() {
    super.doBarThings();
    //...
  }

}

This is currently not possible, TypeScript will give an error. One can overcome this problem in other languages by using interfaces but solving the problem with those is not possible in TypeScript.

Suggestions are welcome!

Upvotes: 14

Views: 27602

Answers (3)

spierala
spierala

Reputation: 2699

Not really a solution to your problem, but it is worth to consider to use composition over inheritance anyway.

Prefer composition over inheritance?

Upvotes: 1

nomadoda
nomadoda

Reputation: 4942

This is my workaround on extending multiple classes. It allows for some pretty sweet type-safety. I have yet to find any major downsides to this approach, works just as I would want multiple inheritance to do.

First declare interfaces that you want to implement on your target class:

interface IBar {
  doBarThings(): void;
}

interface IBazz {
  doBazzThings(): void;
}

class Foo implements IBar, IBazz {}

Now we have to add the implementation to the Foo class. We can use class mixins that also implements these interfaces:

class Base {}

type Constructor<I = Base> = new (...args: any[]) => I;

function Bar<T extends Constructor>(constructor: T = Base as any) {
  return class extends constructor implements IBar {
    public doBarThings() {
      console.log("Do bar!");
    }
  };
}

function Bazz<T extends Constructor>(constructor: T = Base as any) {
  return class extends constructor implements IBazz {
    public doBazzThings() {
      console.log("Do bazz!");
    }
  };
}

Extend the Foo class with the class mixins:

class Foo extends Bar(Bazz()) 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

Upvotes: 2

Brocco
Brocco

Reputation: 64843

This is possible with interfaces:

interface IBar {
  doBarThings();
}

interface IBazz {
  doBazzThings();
}

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

But if you want implementation for this in a super/base way, then you'll have to do something different, like this:

class FooBase implements IBar, IBazz{
  doBarThings() {}
  doBazzThings(){}
}

class Foo extends FooBase {
  doFooThings(){
      super.doBarThings();
      super.doBazzThings();
  }
}

Upvotes: 2

Related Questions