官术网_书友最值得收藏!

Implementing interfaces

We can use classes and interfaces together by defining the contract in an interface and then implementing the class as per the interface. We specify that a class is implementing a particular interface using the implements keyword.

As an example, we can define an interface for the order detail and then a class that implements this interface:

interface IOrderDetail {
product: Product;
quantity: number;
getTotal(discount: number): number;
}

class OrderDetail implements IOrderDetail {
product: Product;
quantity: number;

getTotal(discount: number): number {
const priceWithoutDiscount = this.product.unitPrice *
this.quantity;
const discountAmount = priceWithoutDiscount * discount;
return priceWithoutDiscount - discountAmount;
}
}

In the preceding example, we've prefixed the interface with I so that readers of the code can quickly see when we are referencing interfaces.

Why would we use this approach? It seems like more code than we need to write. So, what's the benefit? This approach allows us to have multiple implementations of an interface, which can be useful in certain situations.

主站蜘蛛池模板: 喀喇| 威信县| 永清县| 从化市| 扎囊县| 获嘉县| 邯郸市| 惠水县| 宝山区| 肇源县| 托里县| 焦作市| 恩施市| 嘉荫县| 新津县| 新竹县| 保康县| 香河县| 昌乐县| 信宜市| 大兴区| 仙桃市| 临沂市| 梁河县| 陇南市| 石嘴山市| 绥滨县| 民丰县| 共和县| 万源市| 黄梅县| 麻城市| 姜堰市| 正镶白旗| 蓬莱市| 邓州市| 五原县| 南通市| 云林县| 全州县| 绩溪县|