TypeScript Examples

by Shrikrishna Gupta

TypeScript

class Greeting
{
	greet():void
  {
  console.clear();
  console.log("Hello ..!!!");
  console.clear();
  }
}

// This is a single line comment which creates an Instance Object

var obj = new Greeting();
obj.greet();


 let myAdd = ( x: number , y: number): number => { return x+y; }; 
 
 console.log(myAdd(23,21));
 
 // 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 
     if (typeof n3 !== 'undefined') {
        return n1 + n2 + n3;
    }

    
 		return n1+n2;
	}
	var sum = addFunction(10, 20);	//output: 30
 console.log(sum);
  
  
  var addFunction = (n1: number, n2: number, n3: number = 30) : number => {
		//observe parameter n3 has default value
    
       
 		return n1+n2+ n3;
	}

    var sum = addFunction(10, 23230);	// output: 60
   console.log(sum);
   
   // 
   
   let items = [0, 1, null, 'Hi'];
   
   items.forEach((item) => {	console.log(item)}); 
   
   items.forEach((number, index, array) => {
    console.log(array);
		});
   
   	interface Point2D {
	    x: number;
	    y: number;
	}
     var point2D: Point2D = { x: 0, y: 10 }
     
     console.log(point2D.x+point2D.y);
     
//  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
console.log(value);
     
     
//Built-in
//Built-in types in Typescript are number, string, boolean, null, undefined, and void.

 var value1: string = "john"; //can take only string values
 console.log(value1);
 
 
 interface Todo
 {
 	name:string,
  taskdecription:...