TypeScript

TypeScript is a typed superset of Javascript that compiles to plain Javascript. Due to its static typing, the code is easier to understand and debug it. Due to modules, namespaces and OOP support, it’s useful for very large and complicated apps. Angular 2 framework is written in TypeScript.

TypeScript code needs to be compiled into Javascript so it’s easier for us to find the errors in the compilation step itself.

Follow the steps mentioned in this link to install the TypeScript Typescript installationTypescript installation

Here is the simple typescript code which contains all the important concepts.

tsMain.ts


//Class
class Greet {
    constructor(){
      console.log("Greet constructor is called") 
    } 
    greet(name: string):void { 
      console.log("Hello"+name) 
   } 
} 

var obj = new Greet(); 
obj.greet("Bala");

//Inheritance
class Vehicle {
    name: string;
    constructor(name: string) { this.name = name; }
    display(noOfWheels: number = 0) {
        console.log("Vehicle Name: "+this.name+" has " +noOfWheels +" Wheels");
    }
}

class Bike extends Vehicle {
    constructor(name: string) { super(name); }
    display(noOfWheels = 2) {
        super.display(noOfWheels);
    }
}

class Car extends Vehicle {
    constructor(name: string) { super(name); }
    display(noOfWheels = 4) {
        super.display(noOfWheels);
    }
}


let bike = new Bike("Pulsar");
let car = new Car("Honda Accord");

bike.display(2);
car.display(4);



//Abstract Class

abstract class Employee {
    name: string;
    earnings: number;

    constructor(name: string) { this.name = name; }
    abstract calculatePay(): void;    
}

class HourlyContractor extends Employee {
    hoursWorked: number;
    constructor(name: string, hoursWorked: number) { super(name); this.hoursWorked=hoursWorked; }

    calculatePay() {
          this.earnings = 70*this.hoursWorked;
          console.log(this.name + "Earnings:"+this.earnings);
    }
}

class FullTimeEmployee extends Employee {
    hoursWorked: number;
    constructor(name: string, hoursWorked: number) { super(name); this.hoursWorked=hoursWorked; }

    calculatePay() {
          this.earnings = 80*this.hoursWorked;
          console.log(this.name + "Earnings:"+this.earnings);
    }
}

let bob = new HourlyContractor("Bob",30);
let john = new FullTimeEmployee("John",40);

bob.calculatePay();
john.calculatePay();



Follow the below steps to compile and run the Typescript script


1. Compile the typescript with tsc command.It will generate a js file with the same name in the current path.
$tsc tsMain.ts 

2. Then run the generated js file with node as below,

$node tsMain.js
Greet constructor is called
HelloBala
Vehicle Name:Pulsar has 2 Wheels
Vehicle Name:Honda Accord has 4 Wheels
BobEarnings:2100
JohnEarnings:3200

Advertisements