【问题标题】:Why field declaration is must in class as it implements an interface为什么字段声明必须在类中,因为它实现了一个接口
【发布时间】:2019-09-16 14:37:56
【问题描述】:

我想在类的接口实现中明确我的概念。

接口类似于模板,在类实现之前不会产生影响。 (link)

所以如果我定义一个接口为:

interface IVehicle {
    color: string,
    model_no: number,
}

然后我创建一个类:

class Vehicle implements IVehicle {

}

它在类名处给了我红色下划线。为什么我必须在类中再次声明字段,因为它正在实现一个不能获取其字段的接口?

为什么我们必须这样写?

class Vehicle implements IVehicle {
    color: string;
    model_no: number;
}

那么接口的概念是什么,一个类无法获取它实现的接口的字段,如果我不实现接口并直接在类中声明字段怎么办。我在想为什么 TypeScript 的开发者会添加这个东西?它使代码加倍;先做一个接口,在里面声明字段,然后再做一个类(还要加上implements InterfaceName,然后再在那个类中声明这些字段,为什么?

【问题讨论】:

  • 如果你只有一个实现,而且它只实现一个接口,那么同时定义一个接口一个类似乎毫无意义。但是假设您有多个接口实现,或实现多个接口的类(在 ISP 上阅读,SOLID 中的 I)。您还可以在不同的实现中以不同的方式(例如普通属性与 getter 和 setter)来满足接口。
  • 好吧,您可以对接口进行操作。一个接口只是描述了任何消费者有什么,实现可以包含很多其他的东西。对于任何消费者,他们都可以使用IVehicle,因为这是定义的合同,他们不必关心实现是什么样的或仍然存在哪些其他类型的字段。该接口只定义了一个您可以使用的合约
  • 正如您所提到的,界面仅用于合同。也许抽象类可以帮助你。
  • 我的问题仍然存在。我问为什么?
  • 因为您可以根据定义的合同工作,而不是针对具体的实现。为了使您的具体实现起作用,它必须与定义的合同相匹配。

标签: javascript typescript class implements


【解决方案1】:

因为这也是有效的:

interface IVehicle {
    color: string;
    model_no: number;
}

class ClownCar implements IVehicle {
    // can be a subset of original type
    public color: 'red' | 'green' | 'blue';
    public model_no: 250 = 250;
}

class NonEditableCar implements IVehicle {
    // can use getter or setters instead, doesn't have to be normal field
    get color() {
        return 'grey';
    }
    get model_no(){
        return 100;
    }
}

一个接口只是说一个实例将具有这些字段,它没有说它必须匹配那个确切的类型。您在类中的声明指定实现是存储需要初始化的实例变量。

您可以在实现接口的同时缩小实例变量并扩大方法调用签名:

interface VehicleCarrier {
    contents: IVehicle[];
    launch(count: number): void;
}

class AircraftCarrier implements VehicleCarrier {
    // this is more specific, and because the inteface forces you to write it you have to consider that
    // it should be more specific.
    public contents: (Plane | Submarine)[];
    // can extend call signatures for methods
    public launch(count: number, type: 'plane' | 'sub' = 'plane') {}
}

【讨论】:

  • 另外,更重要的是:接口只提供类型签名,类提供实际实现(方法体,数据属性的值)。
  • @Bergi 我将问题解释为需要实施它是显而易见的,这就是为什么需要重新声明它。我的目标是指出声明是实现的一部分。
猜你喜欢
  • 2020-01-16
  • 1970-01-01
  • 2013-10-08
  • 2012-01-23
  • 1970-01-01
  • 2012-08-20
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多