接口中方法的默认实现

时间:2017-10-11 16:32:23

标签: typescript

有没有办法在接口中默认实现方法?不幸的是,我不能在基类中制作它。我觉得这是一个非常简单的问题,但在很长一段时间内找不到合适的解决方案。

/ edit在我的例子中我需要这样的东西:

class A {
  somePropertyA;
  someFunctionA() {
    console.log(this.somePropertyA);
  }
}
class B {
  somePropertyB;
  someFunctionB() {
    console.log(this.somePropertyB);
  }
}
class C {
  // Here we want to have someFunctionA() and someFunctionB()
  // without duplicating code of this implementation.
}

B进入A和C的解决方案扩展B对我来说不是那么理想。

1 个答案:

答案 0 :(得分:4)

没有。接口在运行时不存在,因此无法添加运行时代码,例如方法实现。如果您发布有关您的用例的更多细节,可能会有更具体或更有帮助的答案。

编辑:

啊,你想要multiple inheritance,你可以用JavaScript中的类来做。您可能正在寻找的解决方案是mixins

调整手册中的例子:

class A {
    somePropertyA: number;
    someFunctionA() {
        console.log(this.somePropertyA);
    }

}

class B {
    somePropertyB: string;
    someFunctionB() {
      console.log(this.somePropertyB);
    }

}

interface C extends A, B {}
class C { 
    // initialize properties we care about
    somePropertyA: number = 0;
    somePropertyB: string = 'a';   
}
applyMixins(C, [A, B]);

const c = new C();
c.someFunctionA(); // works
c.someFunctionB(); // works        

// keep this in a library somewhere    
function applyMixins(derivedCtor: any, baseCtors: any[]) {
    baseCtors.forEach(baseCtor => {
        Object.getOwnPropertyNames(baseCtor.prototype).forEach(name => {
            derivedCtor.prototype[name] = baseCtor.prototype[name];
        });
    });
}

这对你有用。也许最终这可以用decorators来减轻痛苦,但是现在上面或类似的东西可能是你最好的选择。

相关问题