![](/img/trans.png)
[英]TypeScript Class Implements Interface with Union Type Field results in Error (2322)
[英]Why field declaration is must in class as it implements an interface
我想清除我在類上實現接口的概念。
接口就像一個模板,在類實現它之前不會產生影響。 (關聯)
因此,如果我將接口定義為:
interface IVehicle {
color: string,
model_no: number,
}
然后我做了一個類:
class Vehicle implements IVehicle {
}
它在班級名稱上給了我紅色下划線。 為什么我必須在類中再次聲明字段,因為它正在實現一個不能獲取其字段的接口?
為什么我們必須這樣寫?
class Vehicle implements IVehicle {
color: string;
model_no: number;
}
那么接口的概念是什么,一個類不能獲取它實現的接口的字段,如果我不實現一個接口,直接在一個類中聲明字段呢? 我在想為什么 TypeScript 的開發人員添加了這個東西? 它使代碼翻倍; 首先創建一個接口,在那里聲明字段,然后創建一個類(還添加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 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') {}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.