我想在实现类上的接口时清除我的概念。
接口就像模板一样,在类实现之前不会产生影响。 (link)
因此,如果我将接口定义为:
interface IVehicle {
color: string,
model_no: number,
}
然后我将课程设置为:
class Vehicle implements IVehicle {
}
在课程名称上给我下划线。为什么我必须在类中再次声明这些字段,因为它正在实现一个不能获取其字段的接口?
为什么我们必须这样写?
class Vehicle implements IVehicle {
color: string;
model_no: number;
}
然后,接口的概念是什么,一个类无法获取其实现的接口的字段,如果我不实现接口并直接在类中声明这些字段,该怎么办。我在想为什么TypeScript开发人员添加了这个东西?它使代码加倍;首先创建一个接口,在其中声明字段,然后创建一个类(也添加implements InterfaceName
),然后再次在该类中声明这些字段,为什么?
答案 0 :(得分: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') {}
}