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