Skip to main content

TypeScript is a typed superset of JavaScript that compiles to plain JavaScript. all about TypeScript (main topics about TypeScript )

TypeScript is an open-source programming language developed and maintained by Microsoft. It is a strict syntactical superset of JavaScript, and adds optional static typing to the language. TypeScript is designed for development of large applications and transcompiles to JavaScript.

https://en.wikipedia.org/wiki/TypeScript

benefits of using typescript



1. it's scalable and fit for large scale projects.

2. run time checking

3. all upcoming features ready to use (javascript)

4. source code compile in mostly es3 or es5 so its run on every browser even on older version of internet explorer.

5. strict type checking which would be not available in javascript .

6. almost all popular libraries support typescript like angular and react.

7.performence is almost the same as javascript or maybe slightly faster than javascript in some cases.


POINT 1

creating a class in typescript

/LET START WITH A CLASS 
class Emp
{
   //string data type
   private name:string;
   //age number type
   private age:number;
  //add a constructor
  constructor(_name,_age)
  {
     this.name=_name;
     this.age=_age;
  }
  //get age
   getAge():number//return type
  {
    return this.age;
  }
  //if you need to update the age
  setAge(_age:number)
  {
    this.age=_age;
  }
}
//make a new instance of class Emp
const manish=new Emp("manish",33);
//now see you can access age but typescript showing you private can access error
//console.log(manish.age)//wrong way
//create a getter setter
 

just copy and paste the code in https://stackblitz.com/


POINT 2

extend your existing class


//let extends the class
class ItEmp extends Emp
{
    constructor(_name,_age)
    {
      //you need super
      super(_name,_age)
    }
}

let manishit=new ItEmp("manish",30); 
//you can access because by default its public method in parent class let make it private in parent

//Property 'getAge' is private and only accessible within class 'Emp'.
//console.log(manishit.getAge())

extends keyword use to extend a class multiple inheritance not allowed in typescript

POINT 3

interface and default parameter and destructuring in typescript

default parameter in javascript (must read)
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Default_parameters

interfaces in typescript (object in javascript)
https://www.typescriptlang.org/docs/handbook/interfaces.html#our-first-interface

destructuring in typescript or javascript (very important when u are dealing with es6)
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment





interface Travel
{
     timeX:number,
     distanceX:number
}
class Animal
{
   private animaltype:string;
   private canBreath:boolean;
   private canRun:boolean|string;
   //second parameter contain default value true
   constructor(_animaltype:string,_canBreath:boolean=true)
   {
      this.animaltype=_animaltype;
      this.canBreath=_canBreath;
   }
   
   //this is like regular javascript destructuring below is typescript method
   public runningSpeed({time=10,distance=60}):number
   {
     
      return "Speed is"+" "+ Math.round(distance/time);
   }

   public runningSpeedType({timeX=0,distanceX=0}):number|string
   {
     
      return "Speed is"+" "+ Math.round(timeX/distanceX);
   }
}
let tiger=new Animal("Wild");
//no need to pass second parameter value untill you really want to update its


//RULE : 3  object destructuring IN TYPESCRIPT

//CHECK OUT 

//try to pass runningSpeed time a string it would not show any type error
console.log(tiger.runningSpeed({time:2,distance:100}))


//try to pass runningSpeed time a string it would not show a type error
console.log(tiger.runningSpeedType({timeX:10,distanceX:100}))

//a parameter can support multiple type like 
//string number
//check out can run property of Animal class



POINT 4
 the (my respect) interface is another topic of typescript they are just are just like object




//real use first


//RULE : 5
//TYPES
let x:number=20; //number typescript
let y:number|string=20;//number and string type
let z:number|string|undefined=undefined//number string and unefined type

//You can use a type alias to make a shorthand for a type:

type wildAnimalType=string|Array<string>;
//like interfaces

type point={
  x:number,
  y:number
}
interface wildAnimal
{
    animalName:wildAnimalType,
    biggerThantheseAnimal:wildAnimalType
}

const lion:wildAnimal={
    animalName:"Lion the king",
    biggerThantheseAnimal:["wolf","fox","cheeta","pinkMan"]
}


//now my wildAnimal wildAnimalType type which can be string or array type but if you want a property to be optional type its easy just do it like it
interface wildAnimal2
{
    animalName:wildAnimalType,
    //add question mark
    biggerThantheseAnimal?:wildAnimalType
}
const dino:wildAnimal2={
    animalName:"dino",
    //biggerThantheseAnimal is optional type so you can skip it
}


//RULE SIX interfaces which is actually object and they are important

//in functions
interface Car
{
   brand?:string,//optional type
   price:number,
   speed?:number,//optional type
}
//so myCar implements car interface
function myCar(car:Car)
{
  console.log(car.price);
}
myCar({price:2000})

//interface can define required and optionalfunction for a class but a class can only extend one class but can implements mutiple instance example below
interface airI
{
    groundFight();
     waterFight();
    skyFight();
}
interface strengthI
{
    setTotalPlanes?(): void;
}
class Army
{
   constructor()
   {

   }
}

//extend Army class 
class airForce extends Army implements airI,strengthI
{
    constructor()
    {
      //must
      super();
    }
       groundFight(){};
    waterFight(){};
    skyFight(){};
   setTotalPlanes(){};
}
var indian=new airForce();
//public
indian.groundFight();
//private not allowed even its show currect result
indian.waterFight();
//because airForce implemnets airI and all function inside airI are requied so airForce need to be implements all these function
//setTotalPlanes is Optional 


POINT 5

complex or compound type and how we can handle complex and compound type in typescript

1. intersection and union types in typescript.

https://www.typescriptlang.org/docs/handbook/advanced-types.html

2. const, let, var in typescript

not related to javascript but this is a very important topic of javascript

read more about it  https://tylermcginnis.com/var-let-const/

3. https://www.typescriptlang.org/docs/handbook/decorators.html decorators are experimental in javascript but typescript and babel.js fully support them.


/RULE 8 - intersection and union type 
type circle={
  radius?:number
}
type rectangle={
   width?:number,
   height?:number,
   area:number
}
//ohhh circle is missing area let fix it using intersection we can solve this problem a very nice video on this topic is 
//https://www.youtube.com/watch?v=MbZoQlmQaWQ

type area=circle&rectangle
//now area 
var mynewSahpe:area={
    radius:10,
    area:100
}


//now what do we mean by union type

let width:number;
let height:number;
//union type or compound type
let area:string|number;

//more complex example
let empName:string;
let empSalary:string|number;
let empMonthSalary:Array<string|number>=[];
//or union typescript
type empType=string|number|Array<string|number>;

//example one for compund type
interface itCompEmp
{
   empName:empType,
   empSalary:empType,
   empMonthSalary:empType;
}
//example 2 for compound type
let newEmp:empType="manish";
//override newEmp;
newEmp=["2000+","20004","2008"];
//not allowed because empType not contain empType type
newEmp=[true,false];


//RULE 9 - read only type
 const serverurl:string="http://abc.com" ;



RULE 5:- implementation of a class, static class, and singleton and genric class in typescript





 //object oriented
 //so here my base class which 
 type weapeanType=string|undefined;
 class Weapen
 {
    private weapeanName:weapeanType;
    private weapenType:weapeanType;
    constructor(_weapeanName:weapeanType,_weapenType:weapeanType)
    {
      this.weapeanName=_weapeanName;
      this.weapenType=_weapenType;
    }
    //get weapeanName
    public getWeapeanName():weapeanType
    {
      return this.weapeanName;
    }
    //get weapen name
     public getWeapeanType():weapeanType
    {
      return this.weapeanName;
    }
 }
//now extend the base class
interface Itarget
{
   air?:boolean|string
   water?:boolean|string
   sky?:boolean|string
}
class Tank extends Weapen
{
  private target:Itarget;
  constructor(_weapeanName:weapeanType,_weapenType:weapeanType)
  {
    //call super method (parent class must in typescript)
    super(_weapeanName,_weapenType)
  }
  public canTarget(target:Itarget)
  {
    this.target=target;
  }
  public getTarget():Itarget
  {
    return this.target;
  }
}
//creating tanks different type
let mytank:Tank=new Tank("Arjun","P1");
mytank.canTarget({air:true,water:"no no no",sky:true});
console.log(mytank.getTarget().water)


//tuple in type script ==============
var tuple1:[string,number];
tuple1=["age",22];
console.log(tuple1[0])

//enum in typescript color 
enum Color {Red = 1, Green = 2, Blue = 4}
let c: Color = Color.Green;

console.log(c);


//static classes in typescript
class Mathop
{
   static add(...agrs)
   {
     return agrs.reduce((a,p)=>{
           return a+=p;
     })
   }
}
console.log(Mathop.add(10,20,30,40));
//Singleton class 
class so
{
   static instance;
   name:string;
   static getInstance()
   {
       if(!this.instance)
       {
           this.instance=new so();
       }
      return this.instance;      
   }
   setName(_name:string)
   {
     this.name=_name;
   }
   getName()
   {
     return this.name;
   }
}
so.getInstance().setName("manish");
console.log(so.getInstance().getName());
//genric classes
export type z = string | number | Array<string | number> | boolean;
class solve<T,U>
{
     
    add(a:T,b:U):z
    {
        if (typeof a === "number" && typeof b === "number")
        {
            return a + b;
        } else if(typeof a==="string" && typeof b==="string")
        {
            return `hello ${a} and ${b}`;
        }
        return false;
    }
}
let num=new solve<number,number>();
console.log(num.add(20,20));
let str=new solve();
console.log(str.add("manish","ranjeet"));

Comments

Popular posts from this blog

Creating a word Scramble game where you can drag and drop the word and create a complete word. (drag and drop word Scramble game).

Creating a word game using  phaser game engine which is a javascript based gaming engine  where u can drag and drop world like Word Scramble Game and complete a given word. your index.html file look like below < html > < head > < script src = "src/phaser.min.js" ></ script > < script src = "src/wordGame.js" ></ script > < script src = "src/main.js" ></ script > </ head > < body > </ body > </ html > 1.    <script src="src/phaser.min.js"></script> required to run the  phaser game engine. 2. rest of the two files deals with game logics      <script src="src/wordGame.js"></script>       <script src="src/main.js"></script> you can download whole project from https://github.com/manishchauhan/wordgame/tree/master just copy and paste the project in your local server and run ...

starting with three.js and react with a very simple example

 1. three.js is undoubtedly the best library to create interactive content for the web in 3d. link https://threejs.org/ a working sample of three with react can be found below https://stackblitz.com/edit/react-7n5qf9?file=src%2FApp.js why choose threejs 1. lightweight  2.fast 3.big community  https://discourse.threejs.org/ 4. even you can use unity or unreal to publish html5 content but i don't think that would be acceptable in many cases. 5. open-source project. i created a running sample with React  https://stackblitz.com/edit/react-7n5qf9?file=src%2FApp.js

A simple binary search tree with generic approach tree can store any type of data. (DFS and BFS)

 1. a binary search tree in c++ using a generic approach with both BFS and DFS approach    working tree    https://www.onlinegdb.com/edit/HkuQLdA-w code=> some properties of binary search tree-> 1. binary search tree is not always a balanced tree.  2. Inorder, traversing gives you sorted data.  3.  best is o(log n) and worst is O(n).  4. left node data is always less than root data and right node data always be greater than root data.  5. red-black tree STL map is a balanced binary search tree. *******************************************************************************/ #include <stdio.h> #include<iostream> #include<queue> using namespace std; template < typename T > class Node {   //can store any type of data private:   //genric data or store any type of data   T data;   //reference of left pointer   Node *left = nullptr;   //reference of right pointer   Node *rig...