0

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

类“这两个”定义实例成员属性'doSmth',但'OtherFinal'类将其定义为实例成员函数。

该消息是绝对符合逻辑的。
是否有其他方法让打字稿看到没有直接实施的方法?

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

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

PS:Same question in Russian.

+0

你知道,我认为从两个类继承是一个非常糟糕的主意。改为使用组合和接口! – Louy

+0

至于你的问题,我认为没有*整洁的解决方案。 – Louy

回答

0

您可以解决此错误,通过改变OtherFinal类使用方法属性doSmth替代方法:

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

请记住,它会结合doSmth到创建的实例OtherFinal

+0

这是一种糟糕的方式,因为它将'doSmth'函数放入每个实例而不是原型:[请参阅已编译的代码](http://www.typescriptlang.org/Playground#src=class%20A%20%7B% 0D 0A%%09doSmth()%20%7B%0D 0A%09%%09console.log( 'doSmth%20from%20OtherFinal')%3B%0D 0A%09%%7D%0D 0A%%7D%0D 0A% %0D%0Aclass%20B%20%7B%0D%0A%20%20%20%20doSmth%20%3D%20()%20%3D%3E%20%7B%20%2F%2F%20notice%第二十条%20change%0D 0A%%20%20%20%20%20%20%20%20console.log( 'doSmth%20from%20OtherFinal')%3B%0D 0A%%20%20%20%20%7D% 0D%0A%7D) – Qwertiy

+0

是否在您的用例中手动设置原型上的方法? 'B.prototype.doSmth = function(){console.log('来自OtherFinal的doSmth'); }' – zlumer

+0

这是一种可能的方式。但是在这种情况下,您必须将复制的方法与未复制的方法分开,当您从一个基类中获取它们时很奇怪。 – Qwertiy