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

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.

主站蜘蛛池模板: 泽普县| 宜君县| 分宜县| 阳山县| 周宁县| 潍坊市| 通河县| 黑河市| 望都县| 五大连池市| 辽阳县| 额济纳旗| 华阴市| 绵竹市| 固始县| 正蓝旗| 土默特左旗| 鄂温| 民和| 阿拉尔市| 东乡县| 青田县| 温泉县| 揭东县| 台安县| 花垣县| 屏南县| 岑溪市| 抚宁县| 庆元县| 安乡县| 庄河市| 兴宁市| 霍州市| 中卫市| 蒲城县| 乌恰县| 克东县| 乌兰浩特市| 靖边县| 千阳县|