Multiple Class Inheritance In TypeScript

2019-06-18 12:39发布

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!

2条回答
我命由我不由天
2楼-- · 2019-06-18 13:32

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
查看更多
兄弟一词,经得起流年.
3楼-- · 2019-06-18 13:35

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();
  }
}
查看更多
登录 后发表回答