2017-09-13 87 views
1

所以我有一個名爲Report的基類,然後我有另一個類從報告稱爲數據表擴展。無法在基類打字稿上調用擴展方法

我寫了Report類的擴展,我希望能夠在我有一個數據表對象時調用它。

簡單的例子:

類在一個文件中寫道

export class Report { 
    id: number; 
    name: string; 
} 

另一類在另一個文件

export class Datasheet extends Report { 
    description: string; 
} 

在這裏,我已經寫了報告類的簡單擴展寫道,在不同的文件

import { Report } from './report'; 

export {}; 

declare module './report' { 
    interface Report { 
     hasName(): boolean; 
    } 
} 

Report.prototype.hasName = function() { 
    return this.name == null || this.name.length > 0; 
}; 

所以現在我創建一個新的數據表,我想調用擴展方法.hasName(),這在打字稿編譯罰款,但是當它被髮送到瀏覽器中,我得到一個錯誤說

m.hasName不是函數

例如,我將要做到這一點(簡單實例)

const m = new Datasheet(); 
const check = m.hasName(); 

爲什麼當編譯好的時候出現錯誤?我正在使用Typescript 2.4.2。

我想寫這個,就像你可以C#對象,並寫入擴展方法。這使我的物體保持乾淨

任何幫助將不勝感激!

+0

有沒有原因你不直接添加'hasName()'方法到Report類? – JasonK

+0

當我將所有內容放入單個文件而無需導入或聲明模塊時,代碼問題適用於我。擴展方法的真名是什麼 - 「hasName」或「hasDescription」?是否在調用'new Datasheet()'之前在瀏覽器中執行對Report.prototype.hasName的賦值? – artem

+0

在您使用它們的文件中,您是否導入模塊擴展?我試過,並在節點上它爲我工作(在聲明中將'hasDescription'更改爲'hasName',假設它是一個錯字) –

回答

0

您在Typescript中不需要prototype語法,編譯器會爲您創建該語法。優選地,您也不需要Object.assign,特別是當問題只能用類語法解決時。

這顯示瞭如何有一個Datasheet延伸Report,以便您可以撥打hasName()

interface IReport { 
    hasName():boolean 
} 

class Report implements IReport { 
    id: number 
    name: string 
    hasName() { 
     return this.name == null || this.name.length > 0; 
    } 
} 

class Datasheet extends Report { 
    description: string 
} 

const m = new Datasheet(); 
const check = m.hasName(); 
+0

但我沒有想直接創建對我的對象的功能 – Gillardo

+0

你不會。如果你編譯我的答案,你會發現javascript和你在文章中寫的一樣:'Report.prototype。hasName = function(){ return this.name == null || this.name.length> 0; };' – Kokodoko

+0

,但是您已經直接針對'Report'對象聲明瞭'hasName()'方法.... – Gillardo