问题
Last time I found out how to force typescript to see methods copied to class prototype from the other place. The ways were about declaring fields:
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
}
}
But now I need to override such method in one of the child classes:
class OtherFinal extends Both {
doSmth() { // Here is an error
console.log('doSmth from OtherFinal');
}
}
Class 'Both' defines instance member property 'doSmth', but class 'OtherFinal' defines it as instance member function.
The message is absolutely logical.
Is there some othe way to make typescript to see the method not implemented directly?
All the ways I know lead to the same problem (links lead to corresponding fiddles):
doSmth: () => void, doSmth: typeof Second.prototype.doSmth;.
I understand that I can just declare a function doSmth() {}, but in this case the rubbish will get into compiled code, so I wouldn't like to go in this way.
PS: Same question in Russian.
回答1:
You can work around this error by changing OtherFinal
class to use method property doSmth
instead of a method:
class OtherFinal extends Both {
doSmth = () => { // notice the change
console.log('doSmth from OtherFinal');
}
}
Keep in mind that it will bind doSmth
to the created instance of OtherFinal
.
来源:https://stackoverflow.com/questions/35658109/imitate-multiple-inheritance-with-overriding