I want a Typescript Mixin to have an abstract method that's implemented by the mixed-into class. Something like this.
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 +"... ")
}
};
Now, this works, but I'd really like to make baseFunc in the mixin be abstract to ensure that it's implemented in Foo. Is there any way of doing this, as abstract baseFunc(s:string);
says I must have an abstract class, which isn't allowed for mixins...
All mixins start with a generic constructor to pass the T through, now these can be abstract.
mR_fr0g, yes, BufferedRequestHandlerMixin is implemented as an abstract class. It's common to implement mixins using abstract classes in Java, as the abstract keyword notes that the class is designed for reuse and isn't mean to be used by itself (it also obviously prevents you from using it by itself).
Mixins are a faux-multiple inheritance pattern for classes in JavaScript which TypeScript has support for. The pattern allows you to create a class which is a merge of many classes. To get started, we need a type which we'll use to extend other classes from.
Mixins are special classes that contain a combination of methods that can be used by other classes. Mixins promote code reusability and help you avoid limitations associated with multiple inheritance.
Anonymous class can not be abstract, but you still can declare local mixin class which is abstract like this:
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 +"... ")
}
};
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With