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

Better Memory management with PixiJS or How to manage cpu and cpu memory in PixiJS.

PixiJS is my favorite framework when i am looking for a web games specially for mobile or desktop  PixiJS is fast blazing fast and you can get a decent FPS even on older device.   so here is my optimization techniques for PixiJs 1. manage your sprites in a better way use spritesheet to reduce the draw calls create big sprite sheet which contain multiple sprites can be draw in gpu with a single draw call. use TexturePacker  https://www.codeandweb.com/texturepacker  best tool when its comes to spritesheet 2. for floating point calculation round off calculation for example let  speed = 0.75 ; let  position = 100 ; console . log ( Math . round ( speed * position )) 3. don't create very big canvas when u need a big canvas size game just try to create a small canvas and translate it. 4. its very important one managing TextureCache in memory you can get all TextureCache list by using  Object.entries(PIXI.utils.TextureCache); so even you use ap...

adding particles Effect in pixijs using https://pixijs.io/pixi-particles-editor/

adding particle in pixijs is very easy using the below tool more information can be found below https://github.com/pixijs/pixi-particles https://pixijs.io/pixi-particles-editor/ required packages  /// < reference path = "node_modules/pixi-particles/ambient.d.ts" /> import 'pixi-particles' code of particle delcare a     global variable   private emitter ?: Emitter ; const img = PIXI . Texture . from ( "./assets/images/particle.png" ); this . emitter = new Emitter ( this ,[ img ],{ "alpha" : { "start" : 0.62 , "end" : 0.39 }, "scale" : { "start" : 0.1 , "end" : 0.9 , "minimumScaleMultiplier" : 1.25 }, "color" : { "start" : "#ffff8f" , "end" : ...