我希望一个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 +"... ")
}
};
现在,这很有效,但我真的很想让mixin中的baseFunc成为抽象的,以确保它在Foo中实现。有没有办法做到这一点,因为abstract baseFunc(s:string);
说我必须有一个抽象类,这是不允许mixins ......
答案 0 :(得分:6)
匿名类不能是抽象的,但你仍然可以声明像这样抽象的本地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 +"... ")
}
};