未完全实现的接口

时间:2016-08-15 16:26:30

标签: typescript

以下是官方文档中的示例:

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: Date) {更改了setTime(d) {。所以现在我们没有完全实现ClockInterface,但TypeScript并没有对此提出警告。如果我们使用IntelliSense,类型建议中只有任何

new Clock(3,5).setTime("d: any") // <-- not implemented

那么为什么没有编译器警告我们呢?

1 个答案:

答案 0 :(得分:0)

直接来自typescript specification

  

请注意,因为TypeScript具有结构类型系统,所以类不需要显式声明它实现了一个接口 - 它只需包含适当的实例成员集就足够了。类的implements子句提供了一种机制来断言和验证该类包含适当的实例成员集,但是它对类类型没有影响。

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