TypeScript Complete Course With Completed Hands-on

 

 Introduction to TypeScript

Typescript is a superset of Javascript. It acts like icing on the cake enhancing the power of JavaScript. It can be used for safer coding of large applications. This course introduces you to the following aspects of coding a Typescript program.


Introduction to TypeScript

  • TypeScript Grammar
  • Data Types
  • Object Oriented way Of Programming
  • Inheritance and Polymorphism
  • Modules and Decorators


TypeScript is superset of JavaScript.

  • When a TypeScript code is compiled, it results in a JavaScript code and thus it can run at all instances where JavaScript can run.
  • TypeScript can be visualized as a syntactic add-on for JavaScript.
  • The syntax includes all features of ECMAScript 2015 as well as classes and modules, hence it is object oriented.
  • TypeScript is centralized around the experience of static typing for JavaScript development.


TypeScript vs ES6 vs ES5

  • In ES5, finding bugs at the time of development converts into nightmare sometimes.
  • Plethora of functionality like arrow functions, classes, template strings, destructuring, parameters, iterators, generators, modules, map, set, symbols and promises are added to Javascript by ES6. These are discussed in detail in ECMAScript2015.
  • The proverb Prevention is better than cure suits for TypeScript as it tries to recognize the bugs at an early stage of typing.
  • It is better to write safe codes rather than focusing on less code. This is what TypeScript is circumscribed to.
  • The value of ES6 is in writing Less Code, whereas the value of Typescript is in writing Safe code.


Static vs Dynamic Type Checking :

A Type System is a set of rules that assign a property called type to various construct a computer program consists of, such as variables, expressions, functions or modules. Type checker is responsible for Type checking. It is a kind of program analyzer verifying the types that are being used in the code. The sole purpose is to recognize the bugs before the execution of the code.


There are two types of type checking:

  1. Static Type Checking
  2. Dynamic Type Checking

Static Type Checking is done at compile time. The type of variable should be declared before using them. Examples of programming languages using Static Type Checking are C, C++, JAVA, C#, Fortran, Pascal, Scala etc.

var n: number;  // declaration - required in static type checking

n=5; // definition - can be done later or in declaration

var m=6;


Dynamic Type Checking is done at run time. We do not have to declare the type of variables.

The compiler automatically detects the type. Examples are JavaScript, Python, VBScript etc.

/* JavaScript code */

n=5;

        m=6;

       sum=n+m;

  • TypeScript has a distinctive feature of supporting the static typing. It concludes that we can declare the type of variable/ parameter/ function return.
  • Static typing finds its use only within TypeScript. When converted to a .js file, it has no more role there.
  • The main motive is to use it to compile time checking that ensures the right values are passed to each variable, making sure that the program behavior is same as expected.
  • In TypeScript, we define a type by just appending the variable name with colon followed by the type name as shown in below examples:

Defining Variables

var num: number = 3;

TypeScript infers the type with the value with which we would have initialized the variable. If we do not initialize the variable nor define a type when declaring a variable, TypeScript assigns “any” type to the variable.

var num = 3; // variable num is of type "number"

var num; // variable num is of type "any"

Defining Arrays

    let list: number[] = [1, 2, 3];

Type Annotation - Functions and Objects

Defining Functions

  let myAdd = ( x: number , y: number): number => { return x+y; }; 

// first two "number" defines type for parameters 'x' and 'y'

// third "number" defines `return type` of function

We can define optional parameter by adding “?” so that anyone calling that function may or may not pass value for that variable. Optional parameters do not exist in JavaScript and hence those will not be handled.

var addFunction = (n1: number, n2: number, n3?: number) : number => {

//observe "?" in parameter n3

//Optional parameter has to be the last parameter in the list 

}

var sum = addFunction(10, 20); //output: 30

We can define any parameter with a default value, and while calling the function, we are not required to pass the value of the parameters.

var addFunction = (n1: number, n2: number, n3: number = 30) : number => {

//observe parameter n3 has default value

}

    var sum = addFunction(10, 20); // output: 60


function addnum(a: number, b: number) : number {

    if(typeof a == "string"){

        if(isNaN(parseInt(a,10))){

            return 0;

        }

        a = parseInt(a,10);

    }


    return a + b ;

}

console.log(addnum("10",20));

Data Type Classification

In TypeScript, data types can be classified in three ways:

any

It implies that the variable can take any type of value, which denotes a dynamic type

 var value: any = 30;  //can take string, number, boolean anything

Built-in

Built-in types in Typescript are number, string, boolean, null, undefined, and void.

 var value: string = "john"; //can take only string values

Difference between null and undefined

null - variable is set to an object whose value is undefined (empty)

undefined - variable has no value or object assigned to it.

User-defined

User-defined types include enums, classes, interfaces, arrays etc.

 interface ToDo {

  name: string;

  completed?: boolean; 

  // ? tells that 'completed' is optional property, user need not give value

 }

 let todo: ToDo = {

  name: 'some string'; 

 }

Getting Dirty With TypeScript Code

  • Let us look at some example codes written in TypeScript:
  • Let us start TypeScript with conventional "Hello World" program as shown below.

 class Greeter{

  greeting : T;
  constructor (public greeting : T) { this.greeting = greeting; }
  greet() {
     return "<h1>" + this.greeting + "</h1>";
  }
}
var greeter = new Greeter <string>("Hello world");

document.body.innerHTML = greeter.greet();

Following is a function to calculate Volume Of Cuboid and display result in web page.

  function volumeOfCuboid(length: number, width: number, height: number){

   var volume= length*width*height;

   return "Volume of the Cuboid is: " + volume;

  }

  document.body.innerHTML = volumeOfCuboid(1,2,3);


Find the Length of Arrays hands-on 1 : 

'use strict';

 process.stdin.resume();

 process.stdin.setEncoding('utf-8');

 let inputString: string = '';

 let inputArray: any[];

 process.stdin.on('data', function(inputStdin: string): void {

     inputString += inputStdin;

     let elms:any[] = inputString.split(" ");

     let type = elms[0];

     elms.splice(0,1);

    if(parseInt(type) == 0) {

     for(let i=0;i<elms.length;i++) {

          elms[i] = parseInt(elms[i])

      }

     }

     inputArray = elms;

 });

 process.stdin.on('end', function(): void {

     // now we can read/parse input

     let result: number = arrLength(inputArray);

     console.log(result.toString())

 });

function arrLength(input:any) : number {

    return input.length;

}

Generics

  • Generics are templates allowing the same function to accept arguments of various different types.
  • Generics create the components that are capable of working over data of present and future. It gives us the most dynamic capabilities for developing real time large scale software systems. C# and Java use generics enabling us to create a component that can work over a variety of types rather than a single one.
  • You can implement Generics by writing "T" instead of any specific data type like- number, boolean etc. as shown below.

 function calVolumeCube<T>(side: T): T {

     return side*side*side;

 }

  • To explicitly define type of arguments in function call, you can use <> (angular brackets) as shown below.
    • let volume = calVolumeCube <number> (5);
  • Else compiler will decide the type based on argument you pass as shown below.
    • let volume = calVolumeCube (5);
  • "T" is used to capture type sent by user.

Generics VS any

Let us consider an example.

    function identity<T>(arg: T): T {

        return arg;

    }

While any might look like generic, as that accepts any and all types of values for variable "arg", we are actually losing the information about what that type was when the function returns. If we pass in a number, the only information we have is that any type could be returned.

In contrast, Generics knows which type of data is to be returned.

Enum :

Enum is a way to organize set of related values. Enum members have numeric value associated with them and can be either constant or computed. By default first member of enum is assigned value 0 (zero). Then each subsequent member is assigned value incremented by 1 automatically.

    enum CardSuit {

        Clubs,

        Diamonds,

        Hearts,

        Spades

    }

    // Sample usage

    var card = CardSuit.Clubs;

    // Safety

    card = "some string"; // Error : string is not assignable to type CardSuit

enum myConstant {

   pi = 3.14,

   log5 = 0.7,

   e = 2.73,

   log2 = 1

}

var radius = 2 * myConstant.pi * 10;

console.log(radius);

Object Oriented Programing 

One of the most lovable aspect of TypeScript is that it allows you to structure the code more neatly in classes. TypeScript has built-in support for class based object oriented programming.

There are four main principles to Object Oriented Programming

  1. Encapsulation
  2. Inheritance
  3. Abstraction
  4. Polymorphism.

TypeScript can implement all four of OOPs principles with its smaller and cleaner syntax.

Classes

We can define the scope of variable inside classes as public or private. It is important to note that the public or private keywords are only available in TypeScript.

class Student {

 private firstName: string;  //private members

 private lastName: string;

 yearOfBirth: number;    //Public scope by default

 schoolName: string;

 city: string;

    //Constructor            

    constructor(firstName: string, lastName: string, schoolName: string, city: string, yearOfBirth: number) {

            this.firstName = firstName;

         this.lastName = lastName;

         this.yearOfBirth = yearOfBirth;

         this.city = city;

         this.schoolName = schoolName;

     }

    age() {

        return 2017 - this.yearOfBirth;

    }    

    printStudentFullName(): void {

        alert(this.lastName + ',' + this.firstName);

    }

}

Another example of class and Oject 

class Animal {

    name: String;

    constructor(name:string){

        this.name = name;

    }

    walk(distance:number){

        console.log("Hey my name is "+this.name+" wakign distance "+distance);

    }

}

let animalObj = new Animal("Dave");

animalObj.walk(10);

Interface helps in detecting error in compile time.

Interface Volume {

length: number;

width: number;

sayHi: () => string;

}

//Volume binding object Physics to define all members as specified by interface 

var Physics: Volume = {

length: 10,

width: "ten",

sayHi: (): string => { return "Hello" }

}

interface Player{

    run(): void;

    addLives(num : number) : void;

    score(sc : number ) : number;

}

function createPlayer()  : Player{

    return {

         run : function() {},

         addLives : function(num : number){},

         score : function(sc : number) {return 1;}

    }

}

var newPlayer = createPlayer();

Inheritance

JavaScript uses prototypical inheritance instead of classical inheritance.

TypeScript allows us to inherit from existing classes according to need. Here is a code snippet to explain:

class Cube {

length: number;

constructor(length : number) {

this.length = length;

}

           }

class Physics extends Cube {

color: string;

constructor(length: number, color: string) {

super(length);

this.color = color;

}

}

var obj = new Physics(10, "yellow");

Hands-on 2 : Restaurants Code : 

'use strict';

 process.stdin.resume();

 process.stdin.setEncoding('utf-8');

 let inputString: string = '';

 let obj: any;

 let items: string[];

 process.stdin.on('data', function(inputStdin: string): void {

     inputString += inputStdin;

     items = inputString.split(" ");

     obj = new Restaurant(items);

 });

 process.stdin.on('end', function(): void {

     // now we can read/parse input

     obj.list();

 });

class Restaurant{

    public menu : string[];

    constructor(mane : string[]){

        this.menu = mane;

    }

    list(){

        console.log(this.menu);

    }

}


Hands-on 3  : Human Inheritance : 

'use strict';

 process.stdin.resume();

 process.stdin.setEncoding('utf-8');

 let inputString: string = '';

 let obj: any;

 let details: any[];

 process.stdin.on('data', function(inputStdin: string): void {

     inputString += inputStdin;

     details = inputString.split(" ");

     details[1] = parseInt(details[1]);

     obj = new Employee(details[0],details[1],details[2],details[3],details[4]);

 });

 process.stdin.on('end', function(): void {

     // now we can read/parse input

     obj.getInfo();

 });

class Human{

    protected name:string;

    protected age:number;

    constructor(name:string,age:number){

        this.name = name;

        this.age = age;

    }

}

class Employee extends Human{

    department:string;

    batch:string;

    role:string;

    constructor(name:string, age:number, department:string,batch:string,role:string){

        super(name,age);

        this.department = department;

        this.batch = batch;

        this.role = role;

    }

    getInfo(){

        console.log("Name: "+this.name);

        console.log("Age: "+this.age);

        console.log("Department: "+this.department);

        console.log("Batch: "+this.batch);

        console.log("Role: "+this.role);

    }

}

--------------
Polymorphism – Overloading

Is there any overloading in JavaScript?

Yes, function overloading is possible in TypeScript. The following code snippet will demonstrate how:

class Length{

Length(length: number);

Length(length:string);

Length(value: any) {

if (value && typeof value == "number") {

alert("overload 1");

}

if (value && typeof value == "string") {

alert("overload 2");

}

}}

Polymorphism - Overriding

Method Overriding is a mechanism by which the child class redefines the superclass’s method.

The following code snippet will demonstrate how:

class PrinterClass { 

   doPrint():void {

      console.log("doPrint() from Parent called…") 

   } 

class StringPrinter extends PrinterClass { 

   doPrint():void { 

      super.doPrint() 

      console.log("doPrint() is printing a string…")

   } 

var obj = new StringPrinter() 

obj.doPrint()

 Hands-on 4  : Automobile Polymorephism: 

'use strict';

process.stdin.resume();

process.stdin.setEncoding('utf-8');

let inputString: string = '';

let obj: any;

process.stdin.on('data', function(inputStdin: string): void {

    inputString += inputStdin;

    let inputArr: any[] = inputString.split(" ");

    obj = new Car(inputArr[0], parseInt(inputArr[1]));

});

process.stdin.on('end', function(): void {

  // now we can read/parse input

    obj.printInfo();

});

class Automobile{

    protected fuelType :string;

    protected price : number;

    constructor(f: string, price:number){

        this.fuelType= f;

        this.price = price;

    }

    printInfo(){

        console.log("I am automobile");

    }

}

class Car extends Automobile{

    constructor(f: string, p : number){

        super(f,p);

    }

    printInfo(){

        super.printInfo();

        console.log("Fuel Type: "+this.fuelType);

        console.log("Price: "+this.price);

    }

}

-----------------------

Modules

Typescript module is all about maintenance of the code as it becomes more complex by using classes and interfaces. It can further be classified as:

  1. Internal modules
  2. External modules
  3. Logical grouping of classes, interfaces and functions into one unit is named as namespace.

Module and namespace is differentiated below:

module Cube{

   class property{

                    }

        }

whereas namespace as:

namespace Cube{

}

ECMAScript2016 proposes use of Decorators that are currently available as an experimental feature.

Decorator enables us with feature of adding annotations. It can be activated by enabling "experimentalDecorators" compiler. Constructor, properties, parameters and methods can be decorated in TypeScript.

Following is an example of class decorator:

@log

class Physics {

cube: string;

constructor(message: string) {

this.cube = message;

}

helloPhysics() {

    return "Hello! " + this.cube;

    }

}

TypeScript Course Summary

  • In this course, you have learnt about
  • What is Typescript and how it is different from Javascript
  • Type checking and Type annotations
  • Data type classications including built-in and user-defined types
  • Object oriented way of programming with Typescript
  • Modules and Decorators

-------------------------------------------------------------------------------------------------------------------------

Comments

More Related

For Any Help Related to coding exams follow me on Instagram : codingsolution75

Popular Posts

WIPRO Latest Coding Questions with Solutions : 2023

EPAM Latest Coding Questions with Solutions 2023

MindTree Latest Coding Questions with Solutions

Fresco Play Hands-on Latest Solutions

TCS Digital Exam | DCA | Direct Capability Assessment

TCS Wings 1 All Prerequisite

Infosys | InfytTq | Infosys Certification Exam Latest Coding Questions with Solutions

RAKUTEN Latest Coding Questions with Solutions

Cognizant