A class is a template for creating objects with defined properties and behavior. Its constructor receives initialization data, while the new keyword creates an instance from the class. section 4.4.2
Use classes to organize data and operations together:
- Declare properties such as name, price, and an optional category. section 4.4.2
- Initialize properties in the constructor, or use TypeScript’s concise constructor parameters to declare and assign public properties. section 4.4.2 section 2.3.1
- Put behavior in instance methods, which access object properties through this and are invoked through the object. section 4.4.2
- Extend a class with inheritance, calling super to initialize inherited state and customizing the derived class. section 4.4.2
- Access static methods through the class rather than an instance; static methods cannot access instance fields. section 4.4.2
A product model
class Product { constructor(public name: string, public price: number, public category?: string) {} printDetails() { console.log(`Name: ${this.name}, Price: ${this.price}`); } } let hat = new Product("Hat", 100); hat.printDetails(); The constructor creates a Product instance, and the method reads its properties through this. A DiscountProduct can extend Product and pass a discounted price to super. section 4.4.2
Listing 4.23. Defining a class in the main.ts file in the src folder
class Product {
constructor(name: string, price: number, category?: string) {
this.name = name;
this.price = price;
this.category = category;
}
name: string
price: number
category?: string
}
let hat = new Product("Hat", 100);
let boots = new Product("Boots", 100, "Snow Gear");
function printDetails(product : { name: string, price: number,
category?: string}) {
if (product.category != undefined) {
console.log(`Name: ${product.name}, Price: ${product.price}, `
+ `Category: ${product.category}`);
} else {
console.log(`Name: ${product.name}, Price: ${product.price}`);
}
}
printDetails(hat);
printDetails(boots);
Inspect a complete Product class, create two instances, and compare their console output. section 4.4.2
Listing 20.5. The contents of the product.model.ts file in the src/app/model folder
export class Product {
constructor(public id?: number,
public name?: string,
public category?: string,
public price?: number) { }
static fromProduct(p: Product) {
return new Product(p.id, p.name, p.category, p.price);
}
}
Inspect a reusable Angular product model with optional properties and a static fromProduct factory method. section 20.2.1




















