- Learn React with TypeScript 3
- Carl Rippon
- 162字
- 2021-06-10 19:16:35
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.
推薦閱讀
- WildFly:New Features
- Oracle從新手到高手
- 云原生Spring實(shí)戰(zhàn)
- Java Web應(yīng)用開發(fā)技術(shù)與案例教程(第2版)
- 編譯系統(tǒng)透視:圖解編譯原理
- EPLAN實(shí)戰(zhàn)設(shè)計(jì)
- QGIS:Becoming a GIS Power User
- 深入理解Elasticsearch(原書第3版)
- AppInventor實(shí)踐教程:Android智能應(yīng)用開發(fā)前傳
- 一塊面包板玩轉(zhuǎn)Arduino編程
- 打開Go語言之門:入門、實(shí)戰(zhàn)與進(jìn)階
- 小型編譯器設(shè)計(jì)實(shí)踐
- Spring Boot實(shí)戰(zhàn)
- Building Serverless Web Applications
- 優(yōu)化驅(qū)動的設(shè)計(jì)方法