liveBook · Manning

Constructor method

As explained in Essential TypeScript 5, Third Edition

A constructor is a class member that initializes a newly created instance and its properties.

A constructor initializes a new class instance. When code calls a class with `new`, the constructor receives the new object as `this` and assigns its instance properties. In TypeScript, this works much like a JavaScript class constructor, with additional syntax for declaring and assigning properties concisely. section 4.2.7 section 11.3.4

Initialize an instance in JavaScript

In `primer/index.js`: ```js class Product { constructor(name, price) { this.name = name; this.price = price; } toString() { return `Name: ${this.name}, Price: ${this.price}`; } } let hat = new Product("Hat", 100); console.log(hat.toString()); ``` The constructor sets each object's `name` and `price`. The class method is available to instances through the prototype; it is not redefined by the constructor for every object. section 4.2.7

TypeScript normally requires instance properties to be declared explicitly. If a constructor mostly assigns parameters to properties with the same names, parameter properties remove that repetition: an access control keyword on a parameter tells the compiler to create the corresponding property and assign its value. `readonly` carries over to that property. This does not change how callers invoke the constructor. section 11.3.4

Use parameter properties in TypeScript

In `src/index.ts`: ```ts class Employee { constructor(public readonly id: string, public name: string, private dept: string, public city: string) { // no assignments required } writeDept() { console.log(`${this.name} works in ${this.dept}`); } } let employee = new Employee("fvega", "Fidel Vega", "Sales", "Paris"); employee.writeDept(); ``` The four constructor arguments also become instance properties. A conventional parameter can be mixed into the same constructor when it should not become a property. section 11.3.4

Two distinctions matter when extending or replacing this pattern:

  • A subclass constructor calls `super(...)` to run the superclass constructor before using `this`. This is the class-syntax counterpart of calling another constructor function to initialize the same object. section 4.2.7 section 4.2.4
  • A JavaScript constructor function also initializes properties through `this`, but TypeScript does not handle it as elegantly as a class: using it with `new` can leave the created object typed as `any`. An explicit shape type can describe the result; a property check can narrow it where `instanceof` cannot serve as the type guard. section 4.2.3 section 11.2
Listing 4.12 Extending a class in the index.js file in the primer folder
class Product {
    constructor(name, price) {
        this.name = name;
        this.price = price;        
    }
 
    toString() {
        return `toString: Name: ${this.name}, Price: ${this.price}`;
    }
}

class TaxedProduct extends Product {

    constructor(name, price, taxRate = 1.2) {
        super(name, price);
        this.taxRate = taxRate;
    }

    getPriceIncTax() {
        return Number(this.price) * this.taxRate;
    }
    
    toString() {
        let chainResult = super.toString();
        return `${chainResult}, Tax: ${this.getPriceIncTax()}`;    
    }
}

let hat = new TaxedProduct("Hat", 100);
let boots = new TaxedProduct("Boots", 100, 1.3);
 
console.log(hat.toString());
console.log(boots.toString());

The complete JavaScript example shows `TaxedProduct` calling `super(name, price)` before setting its own `taxRate`, then calling a superclass method from an override. section 4.2.7

How Essential TypeScript 5, Third Edition covers it

How deep it goes
Works through property assignment, TypeScript parameter properties, and subclass initialization; contrasts classes with constructor functions and their typing limitations.
Examples
Uses product creation, an employee with parameter properties, and a subclass that initializes a tax rate.
What it assumes
Builds on JavaScript objects, `new`, and `this` while explaining how class constructors relate to constructor functions and prototypes.
What you can do after
Build it from scratch: initialize class instances, shorten repetitive TypeScript constructors, and call a superclass constructor when extending a class.
How it connects
Connects `new`, `this`, prototypes, inheritance, `super`, access control, and `readonly` properties.

Also explained in

Compare how 13 books explain constructor method →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Essential TypeScript 5, Third Edition. The section links point to the parts of the book it draws on.