How to extend the two classes in Typescript

11.1k Views Asked by At

I need to extend the two classes from the same namespace.

for ex:

declare namespace myNameSpace{

   class class1{
       ///some methods will be here
    }
    class class3 extends class1{
      //some method wil be here
    }
    class class2 extends myNameSpace. class3 {
       //some methods will be here
    }
    export namespace  class2 {
       //declaration will be here
     }
}

i need to extend the 'myNameSpace.class1' class as well as 'class2' namespace.

class newClass extends myNameSpace.class1, myNameSpace.class2 {

   constructor() {
    super();
   }
}

If i call the both the classes, i got an error message

classes can only extend a single class

Is there any other way to fix this issue in typescript.

2

There are 2 best solutions below

0
basarat On

Is there any other way to fix this issue in typescript.

TypeScript is single inheritance by design.

0
Daniel Krom On

You can use mixins but you can't override methods (unless you write a custom applyMixins methods)

Using the method:

function applyMixins(derivedCtor: any, baseCtors: any[]) {
    baseCtors.forEach(baseCtor => {
        Object.getOwnPropertyNames(baseCtor.prototype).forEach(name => {
            derivedCtor.prototype[name] = baseCtor.prototype[name];
        });
    });
}

You have to implement (on empty way)

class NewClass implements myNameSpace.class1, myNameSpace.class2 {
   // empty implementation
   public methodFrom1 : ()=>void;
   public methodFrom2 : ()=>number;
   constructor() {
      // no super()
   }
}

now use mixing to actually make it multi extend classes:

applyMixins(NewClass, [myNameSpace.class1, myNameSpace.class2]);

and now you can create the class

const foo = new NewClass()
foo.methodFrom1() // actually calls nameSpace.class1.prototype.methodFrom1