3

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.

Kalai
  • 287
  • 1
  • 5
  • 17
  • 1
    You can create interfaces and implement them in your class. – Rajesh Jan 02 '18 at 04:49
  • 2
    Possible duplicate of [Typescript: How to extend two classes?](https://stackoverflow.com/questions/26948400/typescript-how-to-extend-two-classes) – Rajesh Jan 02 '18 at 04:50
  • Please google problem first. The dupe has very similar title and is the first link on page. – Rajesh Jan 02 '18 at 04:52

2 Answers2

7

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

TypeScript is single inheritance by design.

basarat
  • 261,912
  • 58
  • 460
  • 511
1

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
Daniel Krom
  • 9,751
  • 3
  • 43
  • 44