这里是从官方文档的例子:没有完全实现的接口
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,因此不能满足接口的约定。 –