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

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.

主站蜘蛛池模板: 肥西县| 定远县| 咸宁市| 伊吾县| 茶陵县| 仙桃市| 肥乡县| 千阳县| 周至县| 茂名市| 瓦房店市| 德惠市| 曲松县| 四子王旗| 通江县| 固始县| 特克斯县| 赫章县| 绍兴县| 陵川县| 祁连县| 周宁县| 礼泉县| 枣强县| 屯昌县| 黑河市| 九江县| 黄平县| 多伦县| 江华| 乐安县| 江达县| 桦甸市| 漠河县| 濉溪县| 安溪县| 通城县| 卢氏县| 翁源县| 延川县| 西安市|