TypeScript Inheritance Example

The following shows an example of inheritance in TypeScript. This resembles languages like Java and C#, but comes with peculiarities that are specific to this language.

class Dialog {
    message: String;
   
    constructor(message: String) {
        this.message = message;    
    }
     
    render() {
        console.log(this.message); 
    }
}

class AlertDialog extends Dialog {
     render() {
         console.log("Alert"); 
     }    
}

let ad: Dialog = new AlertDialog("alert message");
ad.render();

One thing I really like is that the child classes inherit the constructor from the top class, if one isn’t defined. If you do want to define one, call super:

constructor() {
  super("Alert message")    
}

By default, all methods are public, but you can define them as protected or private, and they act as expected, although the access level is erased (I haven’t found anything like protected internal or final)

One thing that is also really nice is that the actual Javascript that gets interpreted from TypeScript is not that complex. Here is what it ends up looking like:

var __extends = (this && this.__extends) || function (d, b) {
    for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
    function __() { this.constructor = d; }
    d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};
var Dialog = (function () {
    function Dialog(message) {
        this.title = "Test Title";
        this.message = message;
    }
    Dialog.prototype.render = function () {
        console.log(this.title);
        console.log(this.message);
    };
    return Dialog;
}());
var d = new Dialog("Test Message");
d.render();
var AlertDialog = (function (_super) {
    __extends(AlertDialog, _super);
    function AlertDialog() {
        _super.apply(this, arguments);
    }
    AlertDialog.prototype.render = function () {
        console.log("Alert");
    };
    return AlertDialog;
}(Dialog));
var ad = new AlertDialog("alert message");
ad.render();

Leave a Reply

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