本文介绍了模仿多重继承的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

最后一次我发现了如何强制打字稿从其他地方查看复制到类原型的方法.有关声明字段的方法:

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:

提琴

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');
    }
}

该消息绝对合乎逻辑.
有没有其他方法可以使打字稿看到未直接实现的方法?

The message is absolutely logical.
Is there some othe way to make typescript to see the method not implemented directly?

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

All the ways I know lead to the same problem (links lead to corresponding fiddles):
doSmth: () => void, doSmth: typeof Second.prototype.doSmth;.

我知道我可以声明一个函数 doSmth() {} ,但是在这种情况下,垃圾将进入编译后的代码中,所以我不会喜欢以这种方式.

I understand that I can just declare a functiondoSmth() {}, but in this case the rubbish will get into compiled code, so I wouldn't like to go in this way.

PS:俄语中的相同问题.

推荐答案

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

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');
    }
}

请记住,它将把doSmth绑定到创建的OtherFinal实例.

Keep in mind that it will bind doSmth to the created instance of OtherFinal.

这篇关于模仿多重继承的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-20 19:38