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

Basic classes

Classes have lots of features. So, in this section we'll look at the basic features of a class. We use the class keyword followed by the class name, followed by the definition of the class.

Let's look at this in more depth with the following example:

  1. We could use a class to define the Product type we previously defined as an interface and as a type alias:
class Product {
name: string;
unitPrice: number;
}
  1. We create an instance of our Product class by using the new keyword followed by the class name and parentheses. We then go on to interact with the class, setting property values or calling methods:
const table = new Product();
table.name = "Table";
table.unitPrice = 500;

Notice that when we use this approach we don't need a type annotation for the table variable because the type can be inferred.

Classes have many more features than type aliases and interfaces though. One of these features is the ability to define the implementation of methods in a class.

Let's explore this with an example:

  1. Let's change the OrderDetail type we have been working within previous sections to a class. We can define the implementation of the getTotal method in this class:
class OrderDetail {
product: Product;
quantity: number;

getTotal(discount: number): number {
const priceWithoutDiscount = this.product.unitPrice * this.quantity;
const discountAmount = priceWithoutDiscount * discount;
return priceWithoutDiscount - discountAmount;
}
}
  1. We can create an instance of OrderDetail, specifying a product and quantity, and then calling the getTotal method with a discount to get the total price:
const table = new Product();
table.name = "Table";
table.unitPrice = 500;

const orderDetail = new OrderDetail();
orderDetail.product = table;
orderDetail.quantity = 2;

const total = orderDetail.getTotal(0.1);

console.log(total);

If we run this and look at the console, we should see an output of 900.

主站蜘蛛池模板: 沙洋县| 恭城| 高雄市| 肥城市| 平阴县| 沅江市| 徐闻县| 忻城县| 贵南县| 河东区| 砀山县| 万载县| 龙川县| 通海县| 高雄县| 墨竹工卡县| 长顺县| 铜山县| 察哈| 武川县| 汉源县| 华宁县| 锡林浩特市| 长岭县| 吉木萨尔县| 西城区| 镇坪县| 闽侯县| 乌拉特后旗| 江川县| 澎湖县| 张家口市| 陆川县| 安远县| 新密市| 澜沧| 太康县| 乌鲁木齐市| 自治县| 陈巴尔虎旗| 华坪县|