- Learn React with TypeScript 3
- Carl Rippon
- 303字
- 2021-06-10 19:16:35
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:
- 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;
}
- 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:
- 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;
}
}
- 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.
推薦閱讀
- C++面向?qū)ο蟪绦蛟O(shè)計(jì)(第三版)
- C語(yǔ)言程序設(shè)計(jì)(第2版)
- 深入實(shí)踐Spring Boot
- Java FX應(yīng)用開發(fā)教程
- Unity Virtual Reality Projects
- Java深入解析:透析Java本質(zhì)的36個(gè)話題
- PhoneGap Mobile Application Development Cookbook
- SharePoint Development with the SharePoint Framework
- C語(yǔ)言程序設(shè)計(jì)學(xué)習(xí)指導(dǎo)與習(xí)題解答
- 大模型RAG實(shí)戰(zhàn):RAG原理、應(yīng)用與系統(tǒng)構(gòu)建
- jQuery炫酷應(yīng)用實(shí)例集錦
- 微服務(wù)從小白到專家:Spring Cloud和Kubernetes實(shí)戰(zhàn)
- RealSenseTM互動(dòng)開發(fā)實(shí)戰(zhàn)
- Django 3.0入門與實(shí)踐
- PHP 7從零基礎(chǔ)到項(xiàng)目實(shí)戰(zhàn)