如何在Typescript中扩展这两个类

问题描述 投票:1回答:2

我需要从同一个命名空间扩展这两个类。

对于前:

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

我需要扩展'myNameSpace.class1'类以及'class2'命名空间。

class newClass extends myNameSpace.class1, myNameSpace.class2 {

   constructor() {
    super();
   }
}

如果我调用这两个类,我收到一条错误消息

类只能扩展一个类

有没有其他方法可以解决打字稿中的这个问题。

javascript typescript typescript2.0 typescript1.5
2个回答
4
投票

有没有其他方法可以解决打字稿中的这个问题。

TypeScript是单一继承的设计。


1
投票

您可以使用mixins但不能覆盖方法(除非您编写自定义applyMixins方法)

使用方法:

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

你必须实施(空路)

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

现在使用混合实际上使它成为多扩展类:

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

现在你可以创建这个类了

const foo = new NewClass()
foo.methodFrom1() // actually calls nameSpace.class1.prototype.methodFrom1
© www.soinside.com 2019 - 2024. All rights reserved.