typescript混合类型中的抽象方法

9
我希望有一个Typescript Mixin,其中包含一个抽象方法,并由混合类实现。类似于以下内容。
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 +"...   ")            
    }
};

现在,这个可以工作,但我真的希望将mixin中的baseFunc变为抽象方法以确保在Foo类中实现。但有什么方法可以实现这一点吗?因为abstract baseFunc(s:string);要求使用抽象类,而mixin中不允许使用抽象类...

1个回答

14

匿名类不能是抽象的,但您仍然可以声明本地混入类,该类是抽象的,如下所示:

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 +"...   ")            
    }
};

我以为我试过那个了!为什么 return abstract class... 不起作用?(编辑 - 啊!因为它是匿名的!) - Roddy
2
这个例子丢失了 MyBase 的方法和属性。您可以使用 function Mixin<B extends Constructor<{}>>(Base: B) 进行修复。 - Joe Lapp

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接