我想澄清我在类上实现接口(interface)的概念。
An interface is something like a template which cannot make an impact until a class implements it. (link)
所以如果我将接口(interface)定义为:
interface IVehicle {
color: string,
model_no: number,
}
然后我创建一个类:
class Vehicle implements IVehicle {
}
它在类名处给了我红色下划线。为什么我必须在类中再次声明字段,因为它正在实现一个不能获取其字段的接口(interface)?
为什么一定要这样写?
class Vehicle implements IVehicle {
color: string;
model_no: number;
}
那什么是接口(interface)的概念,一个类不能取到它实现的接口(interface)的字段,如果我不实现接口(interface)直接在类中声明字段怎么办。我在想为什么 TypeScript 的开发者要添加这个东西?它加倍了代码;首先创建一个接口(interface),在其中声明字段,而不是创建一个类(还添加implements InterfaceName
),然后再次在该类中声明这些字段,为什么?
最佳答案
因为这也是有效的:
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)只是说一个实例将有那些字段,它并没有说它必须匹配那个确切的类型。您在类中的声明指定实现是存储需要初始化的实例变量。
您可以在仍然实现接口(interface)的同时缩小实例变量并扩大方法调用签名:
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') {}
}
关于javascript - 为什么字段声明必须在类中,因为它实现了一个接口(interface),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55878484/