- 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.
推薦閱讀
- iOS Game Programming Cookbook
- Instant Node Package Manager
- WebAssembly實戰
- 三維圖形化C++趣味編程
- INSTANT Weka How-to
- Python Network Programming Cookbook(Second Edition)
- Visual Basic程序設計實驗指導(第4版)
- KnockoutJS Starter
- Learning Python Design Patterns
- 從零開始學C語言
- 區塊鏈項目開發指南
- AI自動化測試:技術原理、平臺搭建與工程實踐
- 金融商業數據分析:基于Python和SAS
- 計算機軟件項目實訓指導
- Unity AI Game Programming(Second Edition)