Tips & Tricks

Write Object-Oriented TypeScript: Inheritance

This is part 1 of a 4 part article on how to program in TypeScript using object-oriented techniques. If you’re new to TypeScript, see Get Started Developing TypeScript Apps with WebStorm and the TypeScript docs.

While types are often hailed as the premiere feature of TypeScript, being able to write object-oriented code in ways that are similar to other mainstream languages such as C# or Java is a very important facet of the language.

There are four main principles to object-orientation: Inheritance, polymorphism, encapsulation, and abstraction. In this article, you’ll learn about inheritance.

Inheritance in object-oriented programming

Many applications will have a need for multiple, similar objects that have some differences or specialization to them.

Take, for example, a banking scenario. People expect banks to have multiple types of bank accounts such as a checking, saving, or investment accounts (any many others). If you were to write code separately for each of these without using inheritance, there is a lot of code duplication, especially in the common methods and properties. That makes the code difficult to understand and maintain. It’s also more error prone since we all know how duplicated code is written: copy and paste. Rather than fill all these classes with redundant code, you can inherit one class from another.

Consider the following base class that represents a generic bank account:

// base (parent) class

class BankAccount {
   get balance(): number {
       return this._balance;
   }
   private _balance: number;

   deposit(amount: number): number {
       return this._balance + amount;
   }

   withdraw(amount: number): number {
       if (amount < this._balance ){
           return this._balance - amount;
       }
       else {
           throw new Error("The withdraw amount must be less or equal than the balance.")
       }
   }
}

You can inherit the BankAccount class by using the extends keyword in a child class. In the following example, the CheckingAccount class inherits all the code from the parent class, then adds its own code to apply a monthly fee. The SavingsAccount class also inherits all the base class code, but calculates interest instead. Common code is contained in the BankAccount class while specialized code (chargeFee and calculateInterest) is in the derived classes.

// derived (child) classes

class CheckingAccount extends BankAccount {
    protected monthlyFeeAmount: number = 5.00;
    chargeFee(): number {
        return this.monthlyFeeAmount;
    }
}

class SavingsAccount extends BankAccount {
    private _interestRate;
    public calculateInterest(){
        return this.balance * this._interestRate;
    }
}

When you create instances of child objects, you have access to the base class members as well as the members added to the derived classes, as shown here:

let checking = new CheckingAccount();
checking.deposit(100);
checking.chargeFee();


let savings = new SavingsAccount();
savings.deposit(100);
let interest = savings.calculateInterest();

WebStorm’s autocomplete feature makes calling functions effortless.

auto complete

While building object models, you may have created a class that you want to change to be a base class. Rather than having to modify several lines of code and create files, use WebStorm’s Extract Superclass feature. You can choose exactly what you want to move into a new parent class and what to keep.

refactor superclass

Additionally, WebStorm contains several features that help you build object models. To create a child class quickly, press Alt + Enter on a base class and choose Create Derived Class. WebStorm suggests a name for the child class that you can modify, and add the extends keyword to mark the class as derived.

create a derived class

Many developers like to structure their projects so there is one file per each class as it’s a popular way to organize files in an object-oriented app. To move this class to its own file, press Alt + Enter on the child class name and choose the intention to move the class to its own file.

move class to its own file

Class hierarchies can quickly become large, and as shown previously, they often span across many files. Viewing and navigating class hierarchies is easy in WebStorm when you use the hierarchy tool window (shortcut: Ctrl + H).

navigate classes by hierarchy

Summary

Inheritance is a key feature of object-oriented programming, and TypeScript has made it a first-class feature of the language.

image description