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

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.

主站蜘蛛池模板: 东莞市| 如东县| 连州市| 广汉市| 景德镇市| 松江区| 新宁县| 吉林省| 仁布县| 长岭县| 九龙城区| 滕州市| 兴海县| 青阳县| 德阳市| 阜康市| 海口市| 黔东| 托里县| 阿拉善盟| 台安县| 浦江县| 中牟县| 阿荣旗| 若羌县| 南靖县| 隆化县| 镇巴县| 开封市| 贵阳市| 鄂尔多斯市| 云浮市| 鹤峰县| 昭通市| 朝阳区| 巍山| 化隆| 微山县| 贵州省| 鄄城县| 时尚|