About Me

My photo
I am an innovator, achiever and leaner having more than 10+ year experience in IT industry. I am having experience on various Microsoft technology like .NET, ASP.NET MVC, C#, SQL server. Recently I have moved focus to develop the server less application hence got the experience to working with AWS- Cloud, AWS-Lambda, AWS-S3 bucket, AWS-Web API Gateway and Dynamo DB. I am open source lover, I have used many open source during my tenure like J-query, JQ-grid, node.js, mongo. DB, backbone.js, angular 1.x, and angular 2.0. I am aware about next generation skill like AI, Microsoft cognitive services, development of text based bot and machine learning. I have been working in Accenture since last five year, my current profile is Application Development Lead. Leading an Innovation team, where we have release tons of application for internal as well end client. I am certified application Designer from MIT. and also completed ITIL V3 foundation certification. During my free time, I explore new technologies in area of web , smart solution and artificial intelligent.

Learn TypeScript in 30 min

TypeScript


Typescript is a free and open-source programming language developed and maintained by Microsoft. It is a strict syntactical super set of JavaScript, and adds optional static typing to the language. Typescript is awesome, I highly recommend learning this thing.



lets start with TypeScript , I Hope you would have visual studio 2015 with update 3 , Please check for typescript version 1.8.36.0.(click on help menu), you can add new TypeScript File from web section.





Data-Type

To learning of any language, it is best thing to start with its data type. Type Script support three type of data type.
Build-In Type (number, string, Boolean, void)
User define types (Array, class, interface, array)
And New Data type *Any which is super type of all the datatype (this is equivalent of var in C# to store any anonymous data)


Variable



Variable is place holder which store the value in program. It provides a means to labeling data with a descriptive name so other program can understand the purpose of variable. There is different way to define the variable in Type Script, I have given different variant in comment line.


//var identifier:type-annotation =value;
//var identifier:type-annotation;
//var identifier=value;
//var identifier;

var studentName: string = "student1";
var studentMark: number = 80;
var studentFee: any = 1250.60;
var studentList: Array<string> = new Array<string>("Student1", "Student2", "Student3");



Operator

Most of operator are similar which we have in java-script, I will not go in details. Please refer operator in java-script.                

Arithmetic operators

Logical operators

Relational operators
Bitwise operators
Assignment operators
Ternary/conditional operator

Control Flow Statement

If Condition

   if (condition1) {
            …        }
        else if (condition2) {
            …
        }
        .
        .
        .
        else
        {
           …
        }

Switch

        switch (variable expression) {
            case constant expr1: {
                //statements;
                break;
            }
            case constant expr2: {
                //statements;
                break;
            }
            default: {
                //statements;
                break;
            }
        }
Loops

We can use all type of loop which is available in native JavaScript, only thing we have new keyword “let” to iterates the enumerator object.

var studentList: Array<string> = new Array<string>("Student1", "Student2", "Student3");

for (let item of studentList) {
            document.write(item);
            document.write("<br/>");
        }

Class

Now days’ developers are more switching to java-script framework, any developer from java or .net background can also code in frontend development using Type Script language, Type script is object oriented language which support OOP features like class, inheritance, polymorphism and interface. It provides liberty to developer to use OOP approach to develop any program. Type Script is transpiler which means it take your code and convert in to java-script. So, any back end programmer who having little knowledge about java-script can use type script.

A class in terms of OOP is a blueprint for creating objects. A class encapsulates data for the object. Below is structure of Student class, the class is self-define, how to declare get; set; property and How to add function in class.

class Student {

    //variable decalaration
    private _studentName: string;
    private _studentMark: number;

    //constructor
    constructor(name: string,mark:number) {
        this._studentName = name;
        this._studentMark = mark;
    } 

    //get set of StudentName property
    public get StudentName():string  {
        return this._studentName;
    }

    public set StudentName(value:string) {
        this._studentName = value;
    }

    //get set of StudentNumber property
    public get StudentMark():number {
        return this._studentMark;
    }
    public set StudentMark(value:number){
        this._studentMark = value;
    }

    //Access Modifier - Function Name (parameter) : return type
    public CalculateGrade(name: string, mark: number): string
    {
        var result: string = "";

        if (mark > 90) {
            result = name + ", you got A grade";
        }
        else if (mark > 60) {
            result = name + ", you got B grade";
        }
        else
        {
            result = name + ", you got C grade";
        }
        return result;
    }
}

Create object and initialize the properties and call method of class.

        var objStudent = new Student("Student1",80);
        objStudent.StudentName="Student2";
        objStudent.StudentMark=80;
        var result = objStudent.CalculateGrade("Student3", 80);
        var result2 = obj.StudentName;

Interface

interfaces define contracts between the program and deriving class. Interfaces define properties, methods, and events, which are the members of the interface. Interfaces contain only the declaration of the members. It is the responsibility of the deriving class to define the members.

interface Iprotocol
{
    name: string;
    DownloadFile: () => string;
    UplaodFile: () => string;

}

class FTP implements  Iprotocol {
    name: string = "FTP";
    DownloadFile()
    {
        return "FTP File downloaded Successfull";
    }

    UplaodFile() {
        return "FTP File uploaded Successfull";
    }
}

class SFT implements Iprotocol {
    name: string = "SFT";
    DownloadFile() {
        return "SFT File downloaded Successfull";
    }

    UplaodFile() {
        return "SFT File uploaded Successfull";
    }
}

//method call
var Iprotocol = new FTP ();
Iprotocol.DownloadFile();
Iprotocol.UplaodFile();

Inheritance 

Inheritance allow you to extend functionality of sub class, by inherit the properties and function from parent class. We have manager class where we have inherited employee class properties.
  
class Employee {
    Name: string;
    constructor(name: string) {
        this.Name = name;
    }
}

class Manager extends Employee {
    OfficeLocation: string;
    constructor(name: string, officelocation: string) {
        super(name);
        this.OfficeLocation = officelocation;
    }

    public DisplayMyLocation() : string
    {
        return this.Name + ", your location is " + this.OfficeLocation;
    }
}

//method call
var objManager = new Manager("manager1", "mumbai");
var result3= objManager.DisplayMyLocation();

Polymorphism

Polymorphism is the ability of an object to take on many forms. TypeScript enables polymorphism via method overloading and method overloading as you can see in the example below.

//method overloading
class Add {
    Method(x:string,y:string);
    Method(x:number,y: number): void;

    Method(x:any,y:any): void {
        if ((x && typeof x == "number") && (y && typeof y == "number") ){
            var s: number;
            s = y + x;
            alert("Total" + s);
        }
        else if ((x && typeof x == "string") && (y && typeof y == "string"))
        {
            var s1: string;
            s1 = y + x;
            alert("concat string" + s1);
        }
        else {
            alert("data type error , check input parameter.");
        }
    }
}

 //method call
   var obj1 = new Add();
   obj1.Method(5, 3);
   obj1.Method("Hello", "Typescript");

//method overriding

class Bird
{
    //Method overloading
    EatingHabit(): string
    {
        return "Bird eats grass and grain.";   
    }
}

class Eagle extends Bird  {
    //Method overriding
    EatingHabit(): string {
        return "Eagle eats meat.";
    }
}

 //method call
var objbird:Bird = new Bird();
objbird.EatingHabit();

var objbird: Bird = new Eagle();
objbird.EatingHabit();

Access Modifier

private:only accessible in the class only.
protected:accessible in the class and the derived classes.
public:accessible outside of the class. 

if you don't put a modifier public, private or protected on your member definition then TypeScript will choose the default one which is public.




export/import the module

variables, functions, classes declared in a module are not visible outside the module unless they are explicitly exported using one of the export forms. to consume a variable, function, class, interface, etc. exported from a different module, it has to be imported using one of the import forms.

Addess.ts

    export class Address {
        public streetAdd1: string = "";
        public streetAdd2: string = "";
        public City: string = "";
        public State: string = "";
        public Coutry: string = "";
    }

Customer.ts

import {Address} from "./Address" 
class Customer
{
    constructor() {

    }
    public address: Address = new Address();
    public customerName: string = "";
    public custmerCode: string = "";




I hope , you would have learnt the various features of TypeScript. Happy Learning :) 

3 comments:

Popular Posts