- 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.
推薦閱讀
- 深入核心的敏捷開發:ThoughtWorks五大關鍵實踐
- Monkey Game Development:Beginner's Guide
- Java入門很輕松(微課超值版)
- React Native Cookbook
- The Complete Coding Interview Guide in Java
- 深入淺出Serverless:技術原理與應用實踐
- 精通Python自動化編程
- 微課學人工智能Python編程
- Data Science Algorithms in a Week
- 奔跑吧 Linux內核
- Java高級程序設計
- R語言實戰(第2版)
- 計算機應用基礎(Windows 7+Office 2010)
- Web前端開發精品課:HTML5 Canvas開發詳解
- 匯編語言程序設計