A constructor runs when a class is instantiated. It receives the arguments passed to `new` and performs the setup needed for the new object. In TypeScript, the constructor is named with the `constructor` keyword, not the class name. section 4.4.2 section 2.3.1
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);
Compare the two `new Product(...)` calls. The constructor assigns each argument to a property through `this`; the optional category can be omitted. Both resulting objects can be passed to a function expecting those properties. section 4.4.2
When constructor arguments simply become properties, TypeScript offers a shorter form: put `public` on each parameter and omit the separate property declarations and assignments. A parameter can also have a default value, as `complete` does in `TodoItem`. In a subclass, `super(...)` calls the parent constructor; `DiscountProduct` passes it a price after subtracting the discount. section 4.4.2 section 2.3.1
Listing 18.9. Declaring a dependency in the discountDisplay.component.ts file in the src/app folder
import { Component, Input } from "@angular/core";
import { DiscountService } from "./discount.service";
@Component({
selector: "paDiscountDisplay",
template: `<div class="bg-info text-white p-2 my-2">
The discount is {{discounter.discount }}
</div>`
})
export class PaDiscountDisplayComponent {
constructor(public discounter: DiscountService) { }
// @Input({alias: "discounter", required: true})
// discounter!: DiscountService;
}
Constructors also declare Angular dependencies. Here, `discounter: DiscountService` tells Angular which service the component needs, while `public` makes it available to the template. This replaces passing the shared object through an input property. section 18.2.2












