<tutorialjinni.com/>

Class in TypeScript with Example

Posted Under: Programming, Tutorials, TypeScript on Jan 15, 2017
TypeScript brings class to JavaScript. Classes are the integral part of the object-oriented development. Classes gives the code generalization, code manageability and consistent way to use them in every JavaScript framework popping every now and then.

Let start with the basic structure of a class in TypeScript 2.
class ClassName{
    public variable1: type 
    protected variable2: type 
    private variable3: type 

    constructor (variable1:type, variable2:type,...,variableN:type){
        // TypeScript Constructor initialization Code
    }
    //function/methods
    public functionName1 (variable1:type, variable2:type,...,variableN:type){
        // TypeScript Public function Body
    }
    protected functionName2 (variable1:type, variable2:type,...,variableN:type){
        // TypeScript Protected function Body
    }
    private functionName3 (variable1:type, variable2:type,...,variableN:type){
        // TypeScript Private function Body
    }
    // N functions goes here
}

Example

In this example we create a class of a Box. We will initiliaze the constructor and then compute the volume of the box.
class Box{
    private width: number 
    private height: number 
    private depth: number 
    constructor(w:number,h:number,d:number){
        //init constructor;
        this.width=w;
        this.height=h;
        this.depth=d;
    }
    public computeVolume(){
        let volume=this.width * this.height * this.depth;
        return "<h1> This Volume of the Box is : <em>"+volume+"</em></h1>";
    }
}

// lets create the object

let box=new Box(10,10,2);
document.body.innerHTML = box.computeVolume();
Following JavaScript will be generated after compiling it.
var Box = (function () {
    function Box(w, h, d) {
        //init constructor;
        this.width = w;
        this.height = h;
        this.depth = d;
    }
    Box.prototype.computeVolume = function () {
        var volume = this.width * this.height * this.depth;
        return "<h1> This Volume of the Box is : <em>" + volume + "</em></h1>";
    };
    return Box;
}());
var box = new Box(10, 10, 2);
document.body.innerHTML = box.computeVolume();
After compiling and running the above example it will rendered in the chrome like the below image. Classes in TypeScript
© Tutorial Jinni