2016-08-15 116 views
1

這裏是從官方文檔的例子:沒有完全實現的接口

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 

那麼爲什麼不編譯器警告我們?

+1

最有可能的,因爲如果時刻設定()接受任何東西,它也接受日期,因此確實實現了接口:你可以在時鐘上調用setTime(someDate)。 –

+0

@JBNizet,但setTime()方法只適用於日期,所以如果我們可以將所有參數標記爲任何參數,爲什麼我們需要所有接口。我認爲正是出於這個原因需要接口。 – Wachburn

+1

這不是界面所說的。接口說:「所有實現此接口的類都必須有一個接受日期的setTime方法和一個必須是Date類型的currentTime字段」。這兩者是無關的。時鐘實現了這個接口。現在,如果yourClock.setTime將一個字符串作爲參數,它將會不同,因爲只接受字符串作爲參數的方法不接受Date,因此不能滿足接口的約定。 –

回答

1

那麼爲什麼編譯器不警告我們呢?

因爲any與所有類型兼容:https://basarat.gitbooks.io/typescript/content/docs/types/type-system.html#any

noImplicitAny

爲了防止你的自我越來越猝不及防使用noImplicitAnyhttps://basarat.gitbooks.io/typescript/content/docs/options/noImplicitAny.html

interface ClockInterface { 
    currentTime: Date; 
    setTime(d: Date); 
} 

class Clock implements ClockInterface { 
    currentTime: Date; 
    setTime(d) { // ERROR : implicit Any 
     this.currentTime = d; 
    } 
    constructor(h: number, m: number) { } 
} 
0
從打字稿 specification

注意,因爲打字稿具有結構類型系統,一類並不需要明確指出,它實現了一個

直接接口就足夠了類只包含一套合適的實例成員。類的implements子句提供了一種機制來斷言和驗證該類包含適當的實例成員集,但否則它對類類型沒有影響。

我認爲它很好地回答你的問題。

相關問題