Search code examples
typescriptabstractmixins

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


Solution

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