Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Abstract methods in typescript mixins

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...

like image 783
Roddy Avatar asked Jun 14 '17 22:06

Roddy


People also ask

Can mixin be abstract?

All mixins start with a generic constructor to pass the T through, now these can be abstract.

Is mixin an abstract class?

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).

What are mixins in TypeScript?

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.

What is true about mixins in TypeScript?

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.


1 Answers

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 +"...   ")            
    }
};
like image 110
artem Avatar answered Sep 25 '22 20:09

artem