打字稿mixin中的抽象方法

Rod*_*ddy 6 abstract mixins typescript

我想要一个Typescript Mixin有一个由mixed-into类实现的抽象方法.像这样的东西.

class MyBase { 
}

type Constructor<T = {}> = new (...args: any[]) => T;

function Mixin<TBase extends Constructor<MyBase>>(Base: TBase) {
  return class extends Base {

    baseFunc(s: string) {};

    doA()
    {
        this.baseFunc("A");
    }
  }
};

class Foo extends Mixin(MyBase) {
    constructor()
    {
      super();
    }

    baseFunc(s: string)
    {
      document.write("Foo "+ s +"...   ")            
    }
};
Run Code Online (Sandbox Code Playgroud)

现在,这是有效的,但我真的想让mixin中的baseFunc成为抽象的,以确保它在Foo中实现.有没有办法做到这一点,因为abstract baseFunc(s:string);我必须有一个抽象类,这是不允许mixins ...

art*_*tem 7

匿名类不能是抽象的,但你仍然可以声明像这样抽象的本地mixin类:

class MyBase { 
}

type Constructor<T = {}> = new (...args: any[]) => T;

function Mixin(Base: Constructor<MyBase>) {
  abstract class AbstractBase extends Base {
    abstract baseFunc(s: string);    
    doA()
    {
        this.baseFunc("A");
    }
  }
  return AbstractBase;
};


class Foo extends Mixin(MyBase) {
    constructor()
    {
      super();
    }

    baseFunc(s: string)
    {
      document.write("Foo "+ s +"...   ")            
    }
};
Run Code Online (Sandbox Code Playgroud)

  • 此示例丢失了 MyBase 的方法和属性。您可以使用 `function Mixin&lt;B extends Constructor&lt;{}&gt;&gt;(Base: B)` 来修复。 (2认同)