2016-08-15 74 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子句提供了一种机制来断言和验证该类包含适当的实例成员集,但否则它对类类型没有影响。

我认为它很好地回答你的问题。

相关问题