通过覆盖

时间:2016-02-26 17:31:06

标签: inheritance typescript multiple-inheritance mixins override

Last time我发现如何强制打字稿来查看从其他地方复制到类原型的方法。方法是宣布领域:

Fiddle

class First {
  someMethod() {
    console.log('someMethod from First');
  }
}

function Second() {
  console.log('Second');
}

Second.prototype.doSmth = function () { 
  console.log('doSmth from Second');
}

class Both extends First {
  constructor() {
    console.log('constructor of Both');
    super();
    Second.call(this);
  }

  doSmth: () => void
}

for (let key in Second.prototype) {
  Both.prototype[key] = Second.prototype[key];
}

class Final extends Both {
  doIt() {
    this.someMethod();
    this.doSmth();
    Both.prototype.doSmth(); // ok
    Final.prototype.doSmth(); // ok
  }
}

但是现在我需要在其中一个子类中覆盖这样的方法:

class OtherFinal extends Both {
    doSmth() { // Here is an error
        console.log('doSmth from OtherFinal');
    }
}
  

类'Both'定义实例成员属性'doSmth',但是'OtherFinal'类将它定义为实例成员函数。

这条信息绝对符合逻辑 有没有办法让打字稿看到方法没有直接实现?

我所知道的所有方式导致同样的问题(链接导致相应的小提琴):
doSmth: () => voiddoSmth: typeof Second.prototype.doSmth;

我明白我可以宣布一个功能 doSmth() {},但在这种情况下,垃圾会进入编译代码,所以我不想这样做。

PS:Same question in Russian.

1 个答案:

答案 0 :(得分:0)

您可以通过将OtherFinal类更改为使用方法属性doSmth而不是方法来解决此错误:

class OtherFinal extends Both {
    doSmth = () => { // notice the change
        console.log('doSmth from OtherFinal');
    }
}

请注意,它会将doSmth绑定到已创建的OtherFinal实例。

相关问题