2015-12-04 28 views
1

聲明:我發現很難總結問題標題中的問題,所以如果您有更好的建議,請在評論中告訴我。TypeScript:繼承類中的方法的自引用返回類型

讓我們以下列簡化打字稿類:

class Model { 
    save():Model { 
    // save the current instance and return it 
    } 
} 

Model類有一個save()方法,返回自己的一個實例:一個Model

我們可以像這樣延長Model

class SomeModel extends Model { 
    // inherits the save() method 
} 

所以,SomeModel將繼承save(),但它仍然會返回一個Model,而不是一個SomeModel

有沒有辦法,或許使用泛型,將返回類型save()設置爲SomeModelSomeModel,而不必在繼承類中重新定義它?

回答

1

你很幸運。 Polymorphic this剛剛在TypeScript 1.7出來。升級到TypeScript 1.7,然後刪除顯式返回類型,它將完美工作:

class Model { 
    save() { 
     return this; 
    } 
} 

class SomeModel extends Model { 
    otherMethod() { 
    } 
} 

let someModel = new SomeModel().save(); 
// no compile error since someModel is typed as SomeModel in TS 1.7+ 
someModel.otherMethod(); 
+0

謝謝。剛剛提出你的答案,因爲它回答了這個問題......雖然有一個轉折,但我沒有預料到 - 我會開一個新的問題! – Merott

+0

這是與扭曲的問題:http://stackoverflow.com/questions/34098023/typescript-self-referencing-return-type-for-static-methods-in-inheriting-classe – Merott