Tuesday, March 21, 2017

A Quick Tutorials on TypeScript

#An Overview#
JavaScript was introduced as a language for the client side. The development of Node.js has marked JavaScript as an emerging server-side technology too. However, as JavaScript code grows, it tends to get messier, making it difficult to maintain and reuse the code. Moreover, its failure to embrace the features of Object Orientation, strong type checking and compile-time error checks prevents JavaScript from succeeding at the enterprise level as a full-fledged server-side technology. TypeScript was presented to bridge this gap.

JavaScript + OOPS = TypeScript
ECMASCRIPT5 + ECMASCRIPT6 + Additional Features = TypeScript

#TypeScript Features#
* TypeScript is a typed superset of JavaScript that compiles to plain JavaScript.
* TypeScript is pure object oriented with classes, interfaces and statically typed.
* The popular JavaScript framework Angular 2.0 is written in TypeScript.
* TypeScript can help programmers to write object-oriented programs and have them compiled to JavaScript, both on server side and client side.

#Components of TypeScript#
* Language
* The TypeScript Compiler
* The TypeScript Language Service

#TypeScript - Syntax#
* Modules
* Functions
* Variables
* Statements & Expressions
* Comments

#TypeScript and Object Orientation#
TypeScript is Object-Oriented JavaScript. Object orientation is a s/w development paradigm that follows real-world. Object orientation considers a program as a collection of objects that communicate with each other via mechanism called methods.
TypeScript supports these object oriented components too:

* Object - An object is a real time representation of any entity.
* State - Described by the attributes of an object
* Behavior - Describes how the object will act.
* Identity - A unique value that distinguishes an object from a set of similar such objects.
* Class - A class in terms of OOP is a blueprint for creating objects. A class encapsulates data for the object.
* Method - Methods facilitate communication b/w objects.

#Using Classes in TypeScript#
class Greeter {
    greeting: string;
    constructor(message: string) {
        this.greeting = message;
    }
    greet() {
        return "Hello, " + this.greeting;
    }
}
let greeter = new Greeter("world");
let button = document.createElement('button');
button.textContent = "Say Hello";
button.onclick = function() {
    alert(greeter.greet());
}
document.body.appendChild(button);

#Using Classes in JavaScript#
var Greeter = (function () {
   function Greeter(message) {
       this.greeting = message;
   }
   Greeter.prototype.greet = function () {
       return "Hello, " + this.greeting;
   };
   return Greeter;
}());
var greeter = new Greeter("world");
var button = document.createElement('button');
button.textContent = "Say Hello";
button.onclick = function () {
   alert(greeter.greet());
};
document.body.appendChild(button);

#TypeScript - Types#
The Type System represents the different types of values supported by the language. TypeScript provides data types as a part of its optional Type System. The data type classification is as given below:
1. Any Types - The super type of all data types
2. Built-in Types - Include number, string, boolean, void, null and undefined.
3. User-defined types - Include Arrays, enums, Classes, interfaces etc.

#Variable Declaration in TypeScript#

Declare its type and value in one statement.

var [identifier]:[type-annotation]=value;

Declare its type but no value. The variable will be set to undefined.

var [identifier]:[type-annotation];

 Declare its value but no type. The variable type will be set to any.

var [identifier]=value;

Declare neither value not type. In this case, the data type of the variable will be any and will be initialized to undefined.

var [identifier];


#TypeScript Variable Scope#
The scope of a variable specifies where the variable is defined. The availability of a variable within a program is determined by its scope.
TypeScript variables can be of the following:
* Global Scope: Global variables are declared outside the programming constructs.
* Class Scope: These variables are also called fields. Fields or class variables are declared within the class but outside the methods.
* Local Scope: Local variables, as the name suggests, are declared within the constructs like methods, loops, etc. Local variables are accessible only within the construct where they are declared.

#Operators in TypeScript#
* Arithmetic operators
* Logical operators
* Relational operators
* Bitwise operators
* Assignment operators
* Ternary/conditional operator
* String operator
* Type operator

#TypeScript Functions#
* Defining a Function
* Calling a Function
* Returning Functions
* Parameterized Function

## Rest Parameters ##
 To declare a rest parameter, the parameter name is prefix with three periods.

function addNumbers(...nums:number[]) {
var i;  
var sum:number = 0;

for(i = 0;i<nums.length;i++){
sum = sum + nums[i];
}
console.log("sum of the numbers",sum)
}

addNumbers(1,2,3) //6
addNumbers(10,10,10,10,10) //50


##Default Parameters##
Function params can be assigned values by default.
Syntax:

function function_name(param1[:type],param2[:type] = default_value) { }

#Anonymous Function#
Functions that are not bound to an identifier are called as anonymous functions. These functions are dynamically declared at runtime.
Syntax:

var res = function([args]) {...}

#Recursion and TypeScrip Functions#
* Recursion is a echnique for iterating over an operation by having a function call to itself repeatedly until it arrives at a result.
* Recursion is best applied when we need to call the same function repeatedly with different parameters form within a loop.

function factorial(number) {
if (number <= 0) { // termination case
     return 1;
} else {    
     return (number * factorial(number - 1));// function invokes itself
}
};

console.log(factorial(6));      // outputs 720

#Lamda Functions#
* Lamda refers to anonymous functions in programming.
* Lambda functions are a concise mechanism to represent anonymous functions.
* These functions are also called as Arrow functions.
* Syntax:

([param1, param2, ...param n])=>statement;

#Function Overloads#
* Functions have the capability to operate differently on the basis of the input provided to them.
* TypeScript supports function overloading.

#TypeScript - Numbers#
Properties of Number object:
* MAX_VALUE
* MIN_VALUE
* NaN
* NEGATIVE_INFINITY
* prototype - static property of the Number object.
* constructor - Returns the function that created this object's instance.

#Number Methods#
* toExponential()
* toFixed()
* toLocaleString()
* toPrecision()
* toString()
* valueOf()

#TypeScript Strings#
* Properties - constructor, length, prototype
* Methods - charAt(), charCodeAt(), concat(), indexOf(), lastIndexOf(), localeCompare(), match(), replace(), search(), slice(), split(), substr(), substring(), toLocaleLowerCase(), toLocalUpperCase(), toLowerCase(), toString(), toUpperCase(),valueOf()

#TypeScript Arrays#

Syntax:

var array_name[:datatype];        //declaration
array_name = [val1,val2,valn..]   //initialization

##Array Object##
var arr_names:number[] = new Array(4)
for(var i = 0;i<arr_names.length;i++;) {
arr_names[i] = i * 2
console.log(arr_names[i])
}

#Array Methods#
Methods: contact(), every(), filter(), forEach(), indexOf(), join(), lastIndexOf(), map(), pop(), push(), reduce(), reduceRight(), reverse(), shift(), slice(), some(), sort(), splice(), toString(), unshift()


#TypeScript - Tuples#
* At times, there might be a need to store a collection of values of varied types.
* TypeScript gives us a data type called tuple that helps to achieve such a purpose.
* Syntax:

var tuple_name = [value1,value2,value3,�value n]

#TypeScript Union#
TypeScript gives programs the ability to combine one or two types.

var val:string|number
val = 12
console.log("numeric value of val "+val)
val = "This is a string"
console.log("string value of val "+val)

##Union Type and function parameter##

function disp(name:string|string[]) {
if(typeof name == "string") {
      console.log(name)
} else {
var i;
for(i = 0;i<name.length;i++) {
         console.log(name[i])
      }
}
}

disp("mark")
console.log("Printing names array....")
disp(["Mark","Tom","Mary","John"])

##Union Type and function parameter##

var arr:number[]|string[];
var i:number;
arr = [1,2,4]
console.log("**numeric array**")

for(i = 0;i<arr.length;i++) {
console.log(arr[i])
}

arr = ["Mumbai","Pune","Delhi"]
console.log("**string array**")

for(i = 0;i<arr.length;i++) {
console.log(arr[i])
}

#TypeScript Interfaces#

* An interface is a syntactical contract that an entity should confirm to.
* Interfaces define properties, methods, and events, which are the members of the interface.

##Interfaces and Inheritance##
* An interface can be extended by other interfaces. In other words, an interface can inherit from other interface.
* TypeScript allows an interface to inherit from multiple interfaces.

Single Interface Inheritance

Child_interface_name extends super_interface_name

Multiple Interface Inheritance

Child_interface_name extends super_interface1_name,super_interface2_name,�,super_interfaceN_name

#TypeScript Classes#
* TypeScript is object oriented JavaScript.
* TypeScript supports object-oriented programming features like classes, interfaces, etc.
* A class encapsulates data for the object.
* TypeScript gives built in support for this concept called class.
* TypeScript gets this feature from ES6.

Class Syntax:

class class_name {
//class scope
}

A class can include fields, constructors and functions.

##Class Inheritance##
* TypeScript supports the concept of Inheritance.
* Inheritance is the ability of a program to create new classes from an existing class.
* The class that is extended to create newer classes is called the parent class/super class.
* The newly created classes are called the child/sub classes.
* A class inherits from another class using the 'extends' keyword. Child classes inherit all properties and methods except constructors from the parent class.

* Syntax:

class child_class_name extends parent_class_name

* Inheritance can be classified as: - Single, multiple, multi-level

##TypeScript - Class Inheritance and Method Overloading

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()

##The Static Keyword##

* The static keyword can be applied to the data member of a class.
* A static variable retains its values till the program finishes its execution.
* Static members are referenced by the class name.

class StaticMem {
  static num:number;
 
  static disp():void {
 console.log("The value of num is"+ StaticMem.num)
  }
}

StaticMem.num = 12     // initialize the static variable
StaticMem.disp()      // invoke the static method

##Data Hiding##
A class can control the visibility of its data members to members of other classes. This capability is termed as Data Hiding or Encapsulation.

* public - Has universal accessibility.
* private - only within the class.
* protected - accessible by the members within the same class.

class Encapsulate {
  str:string = "hello"
  private str2:string = "world"
}

var obj = new Encapsulate()
console.log(obj.str)     //accessible
console.log(obj.str2)   //compilation Error as str2 is private

#TypeScript Objects#
An Object is an instance which contains set of key value pairs.
The values can be scalar values or functions or even array of other objects.

Syntax:

var object_name = {
  key1: �value1�, //scalar value
  key2: �value�,
  key3: function() {
 //functions
  },
  key4:[�content1�, �content2�] //collection
};

## Objects as function parameters##

var person = {
  firstname:"Tom",
  lastname:"Hanks"
};
var invokeperson = function(obj: { firstname:string, lastname :string }) {
  console.log("first name :"+obj.firstname)
  console.log("last name :"+obj.lastname)
}
invokeperson(person)

##Anonymous Object##

var invokeperson = function(obj:{ firstname:string, lastname :string}) {
  console.log("first name :"+obj.firstname)
  console.log("last name :"+obj.lastname)
}
invokeperson({firstname:"Sachin",lastname:"Tendulkar"});


##Duck-typing##
* In duck-typing two objects are considered to be of the same type if both share the same set of properties.
* Duck-typing verifies the presence of certain properties in the objects, rather than their actual type, to check their suitability.

interface IPoint {
  x:number
  y:number
}
function addPoints(p1:IPoint,p2:IPoint):IPoint {
  var x = p1.x + p2.x
  var y = p1.y + p2.y
  return {x:x,y:y}
}

//Valid
var newPoint = addPoints({x:3,y:4},{x:5,y:1})

//Error
var newPoint2 = addPoints({x:1},{x:4,y:3})

#TypeScript Namespaces#
A namespace is a way to logically group related code. This is inbuilt into TypeScript unlike in JavaScript where variables declarations go into a global scope and if multiple JavaScript files are used within same project there will be possibility of overwriting or misconstruing the same variables, which will lead to the "global namespace pollution problem" in JavaScript.

* Defining a Namespace

namespace SomeNameSpaceName {
  export interface ISomeInterfaceName {      }
  export class SomeClassName {      }
}

* Nested Namespaces

namespace namespace_name1 {
  export namespace namespace_name2 {
 export class class_name {    }
  }
}

#TypeScript Modules#
* A module is designed with the idea to organize code written in TypeScript.
* Modules are broadly divided into - Internal modules and external modules.

##Internal Module Syntax (old)##
module TutorialPoint {
  export function add(x, y) {
 console.log(x+y);
  }
}

###Namespace Syntax (New)###

namespace TutorialPoint {
  export function add(x, y) { console.log(x + y);}
}

###External Module###
* External module in TypeScript exists to specify and load dependencies b/w multiple external js files.
* If there is only one js file used, then external modules are not relevant.
* There are two scenarios for loading dependents js files from a single main JavaScript file -
1. Client Side - RequireJS
2. Server Side - NodeJS

##Selecting a Module Loader##
* To spport loading external JavaScrit files, we need a module loader.
* This will be another js library.
* For browser the most common lib used is RequireJs.
* This is an implementation of AMD(Asynchronous Module Definition) specification.

##TypeScript - Ambients##
* Ambient declarations are a way of telling the TypeScript compiler that the actual source coe exists elsewhere.
* When we are consuming a bunch of third party js libraies like jquery/angularjs/nodejs we can't rewrite it in TypeScript.

* Defining Ambients

Sample.d.ts
* Syntax:

declare moudle module_Name {
}






No comments:

Post a Comment