【问题标题】:Imitate multiple inheritance with overriding通过覆盖来模拟多重继承
【发布时间】:2016-06-10 01:06:04
【问题描述】:

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”类将其定义为实例成员函数。

消息绝对合乎逻辑。
有没有其他方法可以让 typescript 看到没有直接实现的方法?

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

我知道我可以只声明一个函数 doSmth() {},但是在这种情况下,垃圾会进入编译代码,所以我不想这样。

PS:Same question in Russian.

【问题讨论】:

  • 你知道,我认为从两个类继承是一个非常非常糟糕的主意。改用组合和接口!
  • 至于你的问题,我认为没有neat解决方案。

标签: inheritance typescript multiple-inheritance mixins overriding


【解决方案1】:

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

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

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

【讨论】:

  • 这是一个不好的方法,因为它将doSmth 函数放入每个实例而不是原型:See the compiled code
  • 在原型上手动设置方法是否适合您的用例? B.prototype.doSmth = function() { console.log('doSmth from OtherFinal'); }
  • 这是一种可能的方式。但是在这种情况下,您必须将复制的方法与未复制的方法分开,当您从一个基类中获取它们时,这很奇怪。
猜你喜欢
  • 1970-01-01
  • 2023-03-27
  • 1970-01-01
  • 1970-01-01
  • 2015-02-27
  • 2016-05-25
  • 2019-06-29
  • 1970-01-01
  • 2020-06-08
相关资源
最近更新 更多