這裏是從官方文檔的例子:沒有完全實現的接口
interface ClockInterface {
currentTime: Date;
setTime(d: Date);
}
class Clock implements ClockInterface {
currentTime: Date;
setTime(d: Date) { // remove type declaration and it will be ok.
this.currentTime = d;
}
constructor(h: number, m: number) { }
}
假設在類的實現,我們只用setTime(d) {
改變setTime(d: Date) {
。所以現在我們沒有完全實現ClockInterface
,但是TypeScript並沒有警告我們。如果我們使用IntelliSense會有隻是任何在類型建議:
new Clock(3,5).setTime("d: any") // <-- not implemented
那麼爲什麼不編譯器警告我們?
最有可能的,因爲如果時刻設定()接受任何東西,它也接受日期,因此確實實現了接口:你可以在時鐘上調用setTime(someDate)。 –
@JBNizet,但setTime()方法只適用於日期,所以如果我們可以將所有參數標記爲任何參數,爲什麼我們需要所有接口。我認爲正是出於這個原因需要接口。 – Wachburn
這不是界面所說的。接口說:「所有實現此接口的類都必須有一個接受日期的setTime方法和一個必須是Date類型的currentTime字段」。這兩者是無關的。時鐘實現了這個接口。現在,如果yourClock.setTime將一個字符串作爲參數,它將會不同,因爲只接受字符串作爲參數的方法不接受Date,因此不能滿足接口的約定。 –