简体   繁体   中英

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!

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();
  }
}

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

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

Prefer composition over inheritance?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM