2014-12-03 43 views
0

如何在類型化腳本中重載一個方法。鑑於以下代碼,我有一個實現接口的類。界面有'polymorhpic'方法,但我似乎無法實現它們 - 獲取錯誤「重複的識別符'MyMethod'」。如何在打字稿中重載一種方法?

export class IService { 

    MyMethod(): string; 
    MyMethod(value: string): number; 

} 

export class MyService implements IService { 

    MyMethod(): string { return "hello world;" } 
    MyMethod(value: string): number { return 1; }  

} 
+0

我所知有在打字稿中不可能做到這一點。您可以使用可選參數MyMethod(參數:字符串=「」)創建單個方法:字符串 { if(param ==「」) \t return 1;其他 返回「hello world」; }' – 2014-12-03 12:57:11

+0

是的問題是界面不會讓你這樣做 – MarzSocks 2014-12-03 13:08:49

回答

1

OK我已經設法解決這個問題,你像這樣做,(注意的MyMethod的實際實施涵蓋了所有輸入和返回類型):

export class IService { 

    MyMethod(): string; 
    MyMethod(value: string): number; 

} 

export class MyService implements IService { 

    MyMethod(): string; 
    MyMethod(value: string): number; 
    MyMethod(value: string = ""): any { if(value != "") return 1 else return "hello world"; }  

}