Type Script Command Line

//Install Typescript
>>npm install -g typescript

//Check version of Type Script
>>tsc -v

//Compile Typescript Code
//this would generate javascript file test.js
>>tsc test.ts

//Running js file
>>node test.js

Data Types in Typescript
Typescript allows to declare variable static(optional).If you use static typing then IDE will allow for type safety at compile time.

//Declaring String
let Name: String = "Mugil"; 

//Declaring Number
let Age: number = 25;

//Declaring Boolean
let Gender: boolean = true;

//Declaring Any datatype
let Street: any = 1 (or) "First" (or) true;

var is Function Scoped and let is block scoped
Using var

var foo = 123;
if (true) {
    var foo = 456;
}

console.log(foo); // 456

Using let

let foo = 123;
if (true) {
    let foo = 456;

}
console.log(foo); // 123
//Determined by Type Inference
var firstName = 'Mugil';
var age = 33;

//Determined by Annotation
var LastName: string = 'vannan';

//Not yet Determined 
var Location;

//Not yet Determined 
var Location;

var previousExp = 6 ;

//If you add a number and string it would be string irrespective of order
var totalExp = previousExp + "five";

//result in error
var Exp: number = previousExp + "five";

console.log("Total Exp - " + totalExp)

Interface

interface Person{
    name: String,
    age: number,
    pincode: any 
}

var objPerson:Person = {name: "Mugil", age:33, pincode:600018}

console.log(objPerson.pincode);

Class

class Person{
    private name: string;
    
    constructor(pname: string){
        this.name=pname;
    }    

    displayPerson(): void{
        console.log(this.name);
    }
}

var objPerson = new Person('Piggy');
objPerson.displayPerson();

Importing Namespaces and Modules

  1. Namespace are not widely used for development rather they are used internally. Modules are widely used for development
  2. In namespace you want to use would be imported using reference tag as in ArithmeticTester.ts, the one below. (Output is throwing error)
  3. When using modules the function would be directly added in module ts file as in Arithmetic.ts and referred using import in ArithmeticTester.ts
  4. Modules would be frequently used, the format would be import {FUNCTION_NAME} from ‘MODULENAME’

Namespace Example
Arithmetic.ts

namespace Arithmetic{
    export function Add(pNum1: number, pNum2: number){
        return pNum1+pNum2;
    }
}

ArithmeticTester.ts

/// <reference path="./Arithmetic.ts" />

let Sum = Arithmetic.Add(5,6);
console.log(Sum);

Modules Example
Arithmetic.ts

export function Add(pNum1: number, pNum2: number){
    return pNum1+pNum2;
}

ArithmeticTester.ts

import {Add} from './Arithmetic'

let Sum = Add(5,6);
console.log(Sum);

Output

11

Functions Example

  1. Arguments to function is optional. You can either set default value incase you are not sure about argument passed like in Add function
  2. You are still allowed to not pass any argument using ? in such case you would end up with different out put at runtime. NAN incase of number or undefined incase of string
  3. return type of function is not mandatory and its optional as in displayName function

Arithmetic.ts

//pNum2 would be considered as 0 incase only one argument is passed
function Add(pNum1: number, pNum2: number=0){
    return pNum1+pNum2;
}

function displayName(firstName: string, lastName? : string) : void{
    console.log("Her name is " + firstName + " "+ lastName); 
}
console.log(Add(5, 8));
console.log(Add(5));
displayName("Piggy");

Output

13
5
Her name is Piggy undefined

How to ensure type safety of arguments while using function
While defining function you may want to ensure the argument type passed.In such case you should declare the argument type the function accepts as one below.

In the below code you could see display name with two parameters(firstName and lastName). TypeSafety of second parameter is ensured by making it as string whereas first one could
be of anytype. If you try to pass something other than string as argument to second parameter then compiler would complain for error.

class SampleScript {
    displayName: (firstName, lastName: string) => void = function(firstName, lastName) {
        console.log("My Name is " + firstName + ' ' + lastName);
    }
}

window.onload = function () {
    var objSampleScript = new SampleScript();
    objSampleScript.displayName(101,'Vannan');
}

Output

My Name is 101 Vannan

Object Types
Object types could be function, module, class, interface and literal literals

Object Literals

 var square={h:10, width:10}
 var rectangle:Object ={h:10, width:20}

 //delcaring triangle as object literal
 var triangle:{};
 triangle={side1:10, side2:10, side3:10};

Functions as Object

var multiply = function (num: number) {
        return num * num;
};

//declaration of divide function object
var divide: Function;

divide = function (num1: number, num2: number) {
   return num1 / num2;
};

Object with variable and function

 var rectangle = {
        height:10,
        width:20,
        calculateArea: function() {
            return this.height* this.width;
        }
    };

    console.log(rectangle.calculateArea());
   var experience = {        
        sendExp: function (exp?: number) {
            if (exp < 3)
                return 'Beginner';
            else if (exp > 3 && exp < 6)
                return 'Intermediate';
            else
                return 'Fresher'; 

        }
    };

    console.log(experience.sendExp(5));
    console.log(experience.sendExp());

Output

Intermediate
Fresher

Function taking Object as parameter

var experience = {
        sendExp: function (job: { skill: String, exp?: number}) {
            if (job.exp < 3)
                return 'Beginner in ' + job.skill;
            else if (job.exp > 3 && job.exp < 6)
                return 'Intermediate in ' + job.skill;
            else
                return 'Fresher'; 

        }
    };

    console.log(experience.sendExp({ skill: 'Java' }));
    console.log(experience.sendExp({ skill: 'Java', exp: 5 }));

Output

Fresher
Intermediate in Java

Comments are closed.