官术网_书友最值得收藏!

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:

  1. 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.

  1. 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;
}
  1. 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.
  1. 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.

主站蜘蛛池模板: 仁化县| 邛崃市| 平山县| 五台县| 华安县| 淮阳县| 武鸣县| 平江县| 定兴县| 襄樊市| 寻乌县| 文水县| 延川县| 简阳市| 五华县| 沂水县| 托克托县| 陵水| 石首市| 清流县| 民丰县| 东海县| 普定县| 靖安县| 贡嘎县| 凤阳县| 剑河县| 刚察县| 吉林省| 利津县| 独山县| 正定县| 海兴县| 濉溪县| 青阳县| 虞城县| 邓州市| 许昌市| 内丘县| 临武县| 孟村|