a blog for those who code

Sunday 26 April 2015

Inheritance in TypeScript

In this post we are going to discuss about Inheritance in TypeScript. JavaScript does not have a concept of inheritance whereas TypeScript supports an inheritance model (similar to object-oriented languages). In simple terms Inheritance means that when a class of objects is defined, any subclass or derived class that is defined can inherit the definitions of one or more general classes.


Inheritance in TypeScript


Inheritance means that a subclass or derived class implicitly contains all non-overridden member of the base class.

Example : In this example we have two classes Sports and Cricket as shown below.

class Sports {
    private _name : string;
    constructor(name:string){
this._name = name;
    }
}
//To create a subclass we use extends, A class can only extend one class
class Cricket extends Sports {
    constructor(name:string){
                 // To call the base class member we use super
super(name);
    }
}

Actually we are using super() to call the base class constructor. So in the above example we are passing name up into our base class to update the _name field in base class. One more thing to note here is that you cannot call a super() method if you haven't extended your class from any base class.

Overloading and Overriding


TypeScript supports function overloads( function with the same name but different parameter signature) and overrides (creating a function in a subclass with the same name as the function in the base class but with different functionality). Overloads can be used in a base class or a subclass. Overrides can only be used in a subclass.

Overloads Example :

class Parent{
    constructor(){}
    Foo(value : any){}
}
class Child extends parent{
    constructor() { super(); }
    Foo(value : string ) : void;
    Foo(value : number) : void;
    Foo(value : any ){} //actual function implementation
}

In the above example Foo function is overloaded to support both string and number parameter. Now when we have any parameter type we can actually send string parameter or number parameter.

Overrides Example :

class Parent{
    constructor(){}
    Foo(value : any){}
}
class Child extends parent{
    constructor() { super(); }
    Foo(value : any ){} //actual function implementation
}

In the above example we are overriding a base class function Foo in a subclass function with the same name and parameter signature as the base class. Now we can do different operations in both the functions.

Please Like and Share the CodingDefined.com Blog, if you find it interesting and helpful.

1 comment:

  1. I was a little surprised by the opening statements. Why does prototypical inheritance not qualify as inheritance?

    I actually thought that TypeScript leveraged prototypical inheritance in the resulting JavaScript code.

    ReplyDelete