Learn Type Script Quickly

In thig blog, we will learn Type Script. If you are going to learn Angular then you must be comfortable with TypeScript.

What is TypeScript?

TypeScript is a typed superset of Java Script that compiles the code into JavaScipt.

Type Script Installation

In order to work with TypeScript, first you have to install node package manager from npmjs.com

Once npm installation done, open command prompt and type below command.

npm install -g typescript – This command will install TypeScript globally to your system.

To check version
tsc –version – This will show you the installed version of TypeScript.

Programing with TypeScript

Open Visual Studio 2017 and add a new script file. You can use any editor like Visual Studio Code to write TypeScript code.
Write some java script code in it and save it with name hello.ts

Once saved, go to command prompt and type – tsc hello.ts
You may notice a hello.js file is created parallel to hello.ts file.

Note – tsc is TypeScript Compiler.

Remember – All java script code is also valid in Type Script

To execute the code, go to command prompt and type node hello.js. You will see the output of the file.

Let’s Explore Type Script

We will explore some basics programming syntax in TypeScript for eg  Variables, Classes, Functions, Loops.

var vs let in TypeScript

The main difference between var and let is that var is available to the nearest function where it has declared, but let is available to the code block where it is declared.

Let’s consider below sample code.

var keyword

No error in below code. Absolutely fine code.

function VarKeyword() {
    for (var i = 0; i <= 10; i++) {
        console.log("Current Value of i is - " + i);
    }
    console.log(i + "is accessible here");
}

let keyword

In below code, last line will show error as i is not accessible why because i is declared within for loop and can not be accessible outside for loop.

function LetKeyword() {
    for (let i = 0; i <= 10; i++) {
        console.log("Current Value of i is - " + i);
    }
   console.log(i + "is not accessible here");
}

Hope, it is clear the differences between var and let keyword.

Classes in Type Script

Traditional Java Script uses functions and prototype to make the component re-usable. But it doesn’t give comfort to a programmer who comes from object-oriented approach.

In TypeScript a class can be created to make it re-usable which works on all major browsers.

Below is the sample code to write a class in TypeScript.

class Products {
    public ProductName: string = "";
    public ProductCost: number = 0;
    public ProductStock: number = 0;
    public ProductCategory: string = "";
}

Just to explain you, if you save the above file as Demo.ts in Visual Studio at the same time a .js file with same name will be created and below will be the sample code in .js file which was transpile from above written .ts code (TypeScript).

var Products = /** @class */ (function () {
    function Products() {
        this.ProductName = "";
        this.ProductCost = 0;
        this.ProductStock = 0;
        this.ProductCategory = "";
    }
    return Products;
}());

So, to call the function and properties written in TypeScript file, we will use below HTML code.
First we will

<html>
<head>
    <meta charset="utf-8" />
    <title></title>
    <script src="TSDemo.js"></script>
</head>
<body>
<script>
    var product = new Products();
    product.ProductName = "Dell Laptop";
    product.ProductCost = 50000;
    product.ProductStock = 10;
    product.ProductCategory = "Electronics";
    alert(product.ProductName + " " + product.ProductCost + " " + product.ProductStock + " " +  product.ProductCategory);
</script>
</body>
</html>

Inheritance with Class

TypeScript allows us to use one of the most common object-oriented principal i.e. Inheritance.
Inheritance provides the code re-usability feature.

To use inheritance in Type Script we use extends.
To call method(s) available in parent class we use super keyword.

Let’s demonstrate this by an example.

class Parent1 {
            GetEmpName() {
                return "Ram Kumar";
            }
        }


        class Child1 extends Parent1 {
            Print() {
                let name = super.GetEmpName();
                console.log(name);
            }
        }


        var obj = new Child1();
        obj.Print();

Data Types and Declaration in Type Script

Type Script has following types of data type.

string, number, boolean

class Product
{
    Test() {
        let name: string;
        let cost: number;
        let stock: number;
        name = 'Laptop';
        cost = 10000;
        stock = 5;
    }
}

Loop in TypeScript

Below sample code illustrate while and for loop and are similar to object oriented programming approach.

class Product
{
    TestLoop() {
        var num: number = 1;
        while (num <= 10) {
            console.log(num);
            num++;
        }
    }


    TestForLoop() {
        for (var num = 0; num <= 10; num++) {
            console.log(num);
        }
    }
}

Functions in TypeScript

Syntax to write a function in Type Script is little different from what we have been doing in Object Oriented Programming.

Syntax to write a function in Type Script

<FunctionName>(<Parameters>) :<Return Type>
{
//Function code goes here….
}

In below code, I have written a function called AddProduct which accepts 3 parameters and return boolean

class Product {
    AddProduct(name: string, cost: number, category: string): boolean {
        console.log("Product request for " + name + " which cost is " + cost + " and category is " + category);
        //...Some logic to call service and communicate with DB
        return true;
    }
}

Below is the code written in HTML to call above functions.

<script>
    var prd = new Product();
    var result = prd.AddProduct('Mobile', 10000, 'Electronics');
    console.log(result);
</script>

Arrow Functions

Arrow functions supports in EcmaScript 6 (ES 6)

Below is the normal way to write a function in Java Script in ES 5

let add = function (a, b) {
            return a + b;
        };
var result = add(50, 20);
console.log(result);

Above function can be written using Arrow function in ES 6

let add = (a, b) => a + b;
var result = add(50, 20);
console.log(result);

Array in TypeScript

TypeScript have the concept of Array similar to what we have used in object-oriented programming like C#.

Syntax to write array of integer in TypeScript

class Product {
    ArrayTest(): void {
        var nums = [2, 4, 6, 8];
        console.log(nums[0]);
        console.log(nums[1]);
        console.log(nums[2]);
        console.log(nums[3]);
    }
}

Syntax to write array of string in TypeScript

class Product {
    ArrayTest(): void {
        var city = new Array("Delhi", "London", "Mumbai", "Sydney");
        for (var i = 0; i < city.length; i++) {
            console.log(city[i]);
        }
    }
}

Interface in TypeScript

interface Car {
    color: string;
    manufacturer: string;
}

var Maruti: Car =
{
    color: "Red", manufacturer: "Marutu Suzuki"
}

console.log(Maruti.color);
console.log(Maruti.manufacturer);

Declare function in an Interface

You can see below, I have created an interface Car which has 2 variables and one function called CarCost which returns data of type number.

Learn Type Script

Let’s implement the interface function.

interface Car {
    color: string;
    manufacturer: string;
    CarCost: () => number;
}

var Maruti: Car =
{
    color: "Red", manufacturer: "Maruti Suzuki",
    CarCost: (): number => {return 250000}
}

console.log(Maruti.color);
console.log(Maruti.manufacturer);
console.log(Maruti.CarCost());

Summary –

TypeScript is a free and open source programming language developed by Microsoft.
Transpilation compiles TypeScript to JavaScript so that browser can understand.
TypeScript has a good intellisense support which allows a developer to write code faster. TypeScript follows Object Oriented programming approach.

Please share this blog on social media. Write your comment below in case you have any feedback.

You may like other blogs –

MVC Tutorial
Web API Tutorial
Is Angular JS different from Angular?

Interview Questions and Answers Series –

MVC Interview Questions and Answers
Web API interview questions and answers

Leave a Comment

RSS
YouTube
YouTube
Instagram