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

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.

主站蜘蛛池模板: 扎兰屯市| 永善县| 韶关市| 晋中市| 湟源县| 马边| 大渡口区| 珲春市| 铁岭市| 平利县| 广德县| 博客| 浦县| 五家渠市| 防城港市| 扬州市| 芷江| 崇义县| 镇巴县| 东阳市| 禹城市| 志丹县| 上栗县| 瓦房店市| 辉县市| 伽师县| 五原县| 栖霞市| 会昌县| 沙洋县| 河东区| 庆安县| 余姚市| 长兴县| 长春市| 运城市| 昂仁县| 改则县| 安新县| 特克斯县| 富川|