假設我有一個 DeliveryMethod 介面
interface DeliveryMethod {
specialInstructions: string;
}
在 Order 物件中使用它來指定如何交付該訂單。
class Order {
…
public delivery: DeliveryMethod;
}
目前我有兩種交付方式;店內取貨
interface InStorePickup extends DeliveryMethod {
store: DocumentReference;
carrier: DocumentReference;
authorisedContacts: {
firstName: string;
lastName: string;
phone: string;
email: string;
}[];
}
和裝運
interface Shipment extends DeliveryMethod {
articleId?: string;
carrier: DocumentReference;
recipientDetails: { … }
}
Order 物件只能使用 DeliveryMethod 的擴展/子級(例如 InStorePickup 或 Shipment)創建,但不能使用 DeliveryMethod 基/父介面創建。
這可以通過這樣的聯合型別來實作:
class Order {
…
public delivery: InStorePickup | Shipment;
}
但是,如果將來引入了新的交付方法(例如 CurbsideCollection),那么使用 DeliveryMethods 聯合的任何地方都必須更新。
有沒有辦法更改 DeliveryMethod 以便它只能擴展并指定為一種型別,以便可以使用它的子級,但不能單獨使用它?
uj5u.com熱心網友回復:
有沒有辦法更改 DeliveryMethod 以便它只能擴展并指定為一種型別,以便可以使用它的子級,但不能單獨使用它?
除非我誤解了你的問題,否則這就是介面的作業方式。您不能單獨使用介面。
class Order {
…
public delivery: DeliveryMethod; // Defined as `DeliveryMethod` but can only ever point to a derived type instance
}
換句話說:
val order.delivery = DeliveryMethod() // Does not compile
uj5u.com熱心網友回復:
這是型別別名的一個很好的例子。
在您的情況下,我會重命名DeliveryMethod為DeliveryMethodBase,然后創建一個型別別名DeliveryMethod,它是從 擴展的所有介面的聯合DeliveryMethodBase,并在您需要的任何地方使用該型別。
如果/當您需要擴展聯合時,您只需要在一個地方進行:別名定義。
interface DeliveryMethodBase {
specialInstructions: string;
}
interface InStorePickup extends DeliveryMethodBase {
// ...
}
interface Shipment extends DeliveryMethodBase {
// ...
}
type DeliveryMethod = InStorePickup | Shipment;
class Order {
// …
public delivery: DeliveryMethod;
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/407787.html
標籤:
