liveBook · Manning

Class

As explained in Essential TypeScript 5, Third Edition

A class is a programming construct that defines the structure and behavior of objects of a data type.

Use a class when objects need the same properties and behavior. A constructor initializes each object, while methods define behavior shared by objects created from the class. JavaScript class syntax sits on top of constructor functions and prototypes; it does not replace that runtime model. section 4.2.7

Listing 4.11 Defining 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}`;
    }
}

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

In `primer/index.js`, `Product` initializes `name` and `price` through `this`. Each `new Product(...)` call creates an object whose `toString()` method can use those values. section 4.2.7

TypeScript adds type declarations to the class syntax. Instance properties can be declared with their types, and constructor parameters can have their own types. The compiler emits a JavaScript class, so inspecting generated `dist/index.js` can help distinguish TypeScript declarations from runtime behavior. `instanceof` also narrows a value's type when checking whether it was created from a class. section 11.3

A typed class

In `src/index.ts`: class Employee { name: string; dept: string; constructor(name: string, dept: string) { this.name = name; this.dept = dept; } writeDept() { console.log(`${this.name} works in ${this.dept}`); } } new Employee("Fidel Vega", "Sales").writeDept(); The property declarations describe the instance; the constructor assigns its values. section 11.3

Use `extends` to inherit from another class. A subclass constructor must call `super(...)` to initialize superclass properties; it can then initialize its own. An overriding method can call its superclass version with `super.method()`. A `static` method is called through the class rather than an instance. JavaScript also permits a private method named with `#`; accessing it from outside its enclosing class produces a syntax error. section 4.2.7 section 11.3.7

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());

`TaxedProduct` extends `Product`, calls `super(name, price)` before using `this`, and builds its overridden `toString()` from `super.toString()`. Compare objects made with the default and explicit tax rates. section 4.2.7

A class hierarchy does not override TypeScript's attention to object shapes. When inferring an array type, the compiler may retain only the common features of its elements. If an array must accept several subclasses, annotate it with the intended superclass type rather than relying on inference. section 11.3.7 section 10.2

Listing 11.19 Using a type annotation in the index.ts file in the src folder
...
let data: Person[] = [new Employee("fvega", "Fidel Vega", "Sales", 
    "Paris"), new Customer("ajones", "Alice Jones", "London", 500)];
data.push(new Supplier("dpeters", "Dora Peters", "New York", "Acme"));
...

The explicit `Person[]` annotation lets an array containing `Employee` and `Customer` objects later accept a `Supplier`. It makes the intended common type clear. section 11.3.7

Classes can also model application data. An Angular data model uses regular TypeScript classes for orders and order lines, alongside a `Product` type. Generic type parameters can be used with classes, while decorators can transform class features. section 18.3 section 12.5 section 14.8

How Essential TypeScript 5, Third Edition covers it

How deep it goes
Works through construction, inheritance, static and private methods, typed properties, emitted JavaScript, and subclass-array inference.
Examples
Uses product pricing, typed employees, mixed subclass arrays, and an Angular order data model.
What it assumes
Builds on JavaScript objects and TypeScript types while explaining class construction and its prototype-based runtime behavior.
What you can do after
Build it from scratch: define typed classes and subclasses, then annotate mixed-subclass arrays when inference is too narrow.
How it connects
Connects classes to prototypes, object shapes, type narrowing, inheritance, generic types, and decorators.

Also explained in

Compare how 21 books explain class →

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.