【发布时间】:2016-06-10 01:06:04
【问题描述】:
Last time 我发现了如何强制打字稿查看从其他地方复制到类原型的方法。方法是声明字段:
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”类将其定义为实例成员函数。
消息绝对合乎逻辑。
有没有其他方法可以让 typescript 看到没有直接实现的方法?
我知道的所有方法都会导致同样的问题(链接会导致相应的问题):doSmth: () => void, doSmth: typeof Second.prototype.doSmth;。
我知道我可以只声明一个函数
doSmth() {},但是在这种情况下,垃圾会进入编译代码,所以我不想这样。
【问题讨论】:
-
你知道,我认为从两个类继承是一个非常非常糟糕的主意。改用组合和接口!
-
至于你的问题,我认为没有neat解决方案。
标签: inheritance typescript multiple-inheritance mixins overriding