TypeScript Inheritance


Inheritance is a way for objects or classes to gain access to the properties of classes that are part of other objects. The keyword we use is extends.

Traditional JavaScript uses functions and prototype-based inheritance to build up reusable components, but this may feel a bit awkward to programmers more comfortable with an object-oriented approach, where classes inherit functionality and objects are built from these classes.

Starting with ECMAScript 2015, also known as ECMAScript 6, JavaScript programmers will be able to build their applications using this object-oriented class-based approach. In TypeScript, we allow developers to use these techniques now, and compile them down to JavaScript that works across all major browsers and platforms, without having to wait for the next version of JavaScript.

First we’ll start with a regular class called Person. The TypeScript code is below. Compile it with tsc at the command line. Run it with Node.js using the compiled JavaScript file. The output to the command prompt is: Bran is dancing!

class Person {
    name : string;
    constructor(name:string){
        this.name = name;
    }
    dance(){
        console.log(this.name + " is dancing!");
    }
}
var bran = new Person("Bran");
bran.dance();

Extends

The extends keyword means that this class (AwesomePerson) will automatically start with all of the properties of the class it extends (Person). See the code below. The name, constructor and dance are now part of AwesomePerson and we don’t need to write that code again for AwesomePerson. We can however override the dance function of Person by writing a function with the same name.

class Person {
    name : string;
    constructor(name:string){
        this.name = name;
    }
    dance(){
        console.log(this.name + " is dancing!");
    }
}
var bran = new Person("Bran");
bran.dance();

class AwesomePerson extends Person {
  dance() {
    console.log("So Awesome!");
  }
}
var robb = new AwesomePerson("Robert");
robb.dance();

The output of the above code is Bran is dancing! followed by So Awesome! on the next line.

Super Function

If you want to call the parent class’s function in the child class’s function you need to use super.

class Person {
    name : string;
    constructor(name:string){
        this.name = name;
    }
    dance(){
        console.log(this.name + " is dancing!");
    }
}
var bran = new Person("Bran");
bran.dance();

class AwesomePerson extends Person {
  dance() {
    console.log("So Awesome!");
    super.dance();
  }
}
var robb = new AwesomePerson("Robert");
robb.dance();

Series Navigation<< TypeScript ClassesTypeScript Modules >>

Leave a comment

Your email address will not be published. Required fields are marked *