- 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.
推薦閱讀
- Mastering RabbitMQ
- Vue.js入門與商城開發(fā)實戰(zhàn)
- Vue.js快速入門與深入實戰(zhàn)
- Learning SQLite for iOS
- HTML5+CSS3網(wǎng)頁設計
- 用戶體驗增長:數(shù)字化·智能化·綠色化
- Kotlin從基礎到實戰(zhàn)
- Visual Basic程序設計實驗指導(第二版)
- 持續(xù)輕量級Java EE開發(fā):編寫可測試的代碼
- R語言:邁向大數(shù)據(jù)之路(加強版)
- 零代碼實戰(zhàn):企業(yè)級應用搭建與案例詳解
- uni-app跨平臺開發(fā)與應用從入門到實踐
- Web Developer's Reference Guide
- Mastering SciPy
- Mastering ASP.NET Core 2.0