- Learn React with TypeScript 3
- Carl Rippon
- 265字
- 2021-06-10 19:16:34
Optional properties and parameters
We might want to make a property optional because not every situation where the interface is implemented requires it. Let's take the following steps in our OrderDetail interface:
- Let's create an optional property for the date it was added. We specify an optional value by putting a ? at the end of the property name but before the type annotation:
interface OrderDetail {
product: Product;
quantity: number;
dateAdded?: Date,
getTotal(discount: number): number;
}
We'll see that our implementation of this interface, tableOrder, isn't broken. We can choose to add dateAdded to tableOrder but it isn't required.
- We might also want to make a method parameter optional. We do this in a similar way by putting a ? after the parameter name. In our example, let's make discount optional in the OrderDetail interface:
interface OrderDetail {
product: Product;
quantity: number;
dateAdded?: Date,
getTotal(discount?: number): number;
}
- We can change the method implementation signature as well:
getTotal(discount?: number): number {
const priceWithoutDiscount = this.product.unitPrice * this.quantity;
const discountAmount = priceWithoutDiscount * (discount || 0);
return priceWithoutDiscount - discountAmount;
}
We've also dealt with the case when a discount isn't passed into the method by using (discount || 0) in the discountAmount variable assignment.
x || y is shorthand for if x is truthy then use x, otherwise, use y. The following values are falsy values: false, 0, "", null, undefined, and NaN. All other values are truthy.
- With our optional parameter in place, we can call getTotal without passing a value for the discount parameter:
tableOrder.getTotal()
The preceding line doesn't upset the TypeScript compiler.
推薦閱讀
- Mastering NetBeans
- 深度實(shí)踐OpenStack:基于Python的OpenStack組件開發(fā)
- Developing Middleware in Java EE 8
- ArcGIS By Example
- 劍指大數(shù)據(jù):企業(yè)級數(shù)據(jù)倉庫項目實(shí)戰(zhàn)(在線教育版)
- 微信小程序全棧開發(fā)技術(shù)與實(shí)戰(zhàn)(微課版)
- Getting Started with Nano Server
- Unity 2018 Augmented Reality Projects
- JSP程序設(shè)計實(shí)例教程(第2版)
- H5+移動營銷設(shè)計寶典
- 計算機(jī)組裝與維護(hù)(第二版)
- Swift 2 Design Patterns
- Java程序設(shè)計基礎(chǔ)教程
- C#.NET程序設(shè)計
- Data Visualization:Representing Information on Modern Web