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

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.

主站蜘蛛池模板: 祁门县| 巴林右旗| 云浮市| 桐庐县| 聂拉木县| 偃师市| 娄烦县| 浦东新区| 陇川县| 房产| 静安区| 东海县| 泰宁县| 锡林浩特市| 申扎县| 蓝田县| 工布江达县| 柘荣县| 黎城县| 治多县| 绥阳县| 青神县| 南雄市| 丘北县| 通城县| 海门市| 河间市| 噶尔县| 长武县| 嘉禾县| 衡水市| 会同县| 乌兰县| 阿鲁科尔沁旗| 扶风县| 霸州市| 淮北市| 墨玉县| 阜新市| 监利县| 临潭县|