Typescript

TypeScript is a superset of JavaScript ES6 used mainly in Angular and other applications developed by Microsoft. TypeScript is JavaScript ES6 with Types, Interface and Generics. TypeScript code is Transpiled to JavaScript using TypeScript Compiler.

JavaScript ES6 Code can be used in TypeScript. Basically Any valid JS ES6 Code is TypeScript. Like, we can use both let x=3; or let x:number=3;. TypeScript compiler can transpile both ES6 or TypeScript code to JavaScript. We can also use typescript compiler to Compile JS ES6 to ES5.

TypeScript Advantages

  1. Optional types like string, number
  2. types in parameter and return
  3. Interface
  4. Generics
  5. Better error handling

Prerequisite to learn TypeScript

A frequently asked question is Should i learn TypeScript without JavaScript? The answer in no. TypeScript is JavaScript Superset with additional features. Which means the Syntax and Runtime behavior will remain same.

  1. HTML5
  2. CSS3
  3. JavaScript ES6 and above ( Expertise level )

To Learn JavaScript, visit our free JavaScript Tutorial.



Install TypeScript

TypeScript is available on npm as typescript. We can install the latest stable version or next available beta version. Make sure you have installed Node JS. If not, install Node JS first, because npm comes with Node JS.

Install TypeScript Stable

Install Stable version of typescript.

sudo npm install -g typescript

Install TypeScript Next

Install next version of typescript.

sudo npm install -g typescript@next

Verify TypeScript

Verify whether TypeScript is installed or not.

Version 4.9.3

tsc --version

Transpile

TypeScript files are saved in project with .ts extension. But browser understands only JavaScript (.js files). For that, we need to Transpile .ts file to .js first. Then we can link .js file to our web application or run in Node REPL.

Compile TS

tsc index.ts

Compile TS to JavaScript ES6

tsc index.ts --target es6

Compile TS and run in Node REPL

tsc index.ts --target es6 && node index

Types

TypeScript comes with support for types, like string, numbers etc. Types define the type of datatype.

Types in TypeScript

  1. string
  2. number
  3. boolean
  4. undefined
  5. function
  6. array

String Type


             let x:string="hello world";                
                 

Number Type


             let x:number=3;
                 

Parameter Type


             function sayHi(name: string{ return `Hello ${name}.` }
                 

return Type


             function getArea:number(r: number){ return Math.PI * r * r };
                 

Types by Inference

TypeScript automatically define types by Inference by using his own type-system. This means value is quotes is considered as string.

Like in JavaScript, we cannot change variable with string to another datatype.


  let user="avinash"; // user is string

Like JavaScript, TypeScript doesn't support passing string to numeric variable name or any other datatype. If a variable is declared string, it can store only string data. Passing another datatype value can throw compilation error.

error TS2322: Type 'string' is not assignable to type 'number'.


    let id=3; // id is number
    id="hello"; // error
  


Interface

Interface are used in Objects to defined Types of key. In JavaScript, Object key can have value of any datatype, but in TypeScript, interface can specify the datatype of key.


interface User{
name:string;
id:number;
}  

const user:User={
name:"Avinash",
id:212,
};

Interface with classes


interface User{
name:string;
id:number;
}  

class UserData{
name:string;
id:number;

constructor(name: string, id: number) {
this.name = name;
this.id = id;
}
}

const user: User = new UserData("Avinash", 212);

Generics

Generics provides variables to types, like stringArray, numberArray etc. In JavaScript, Arrays are collection of any datatype, means an array in JavaScript can have both strings and numbers. This can cause problem while sorting. Thats why we pass callback (compare function) in JavaScript to sort numbers.

With generics, an Array can have single datatype values only.

  1. StringArray
  2. NumberArray
  3. ObjectWithNameArray

StringArray

StringArray generic can only store string in array.


  type StringArray=Array<string>;

  const month:StringArray=["jan","feb"];  

NumberArray

NumberArray generic can only store numbers in array.


  type NumberArray=Array<number>;

  const data:NumberArray=[1,3,8,10];
    

ObjectWithNameArray

ObjectWithNameArray generic can only store string in array.


  type ObjectWithNameArray=Array<{name:string}>;

  const cars:ObjectWithNameArray:[
    {name:"swift"},
    {name:"alto"},
  ];


Classes

TypeScript use Classes which was unavailable in JavaScript before ES6. Classes provide neat and clean structure to create constructor objects. JavaScript supports Function based constructors till ES5, now JS supports both Function and Class based constructors.

TypeScript also supports access modifiers ( Public and Private ) which are still not fully implemented in in JavaScript.

If you are not familiar with Classes in JavaScript, just go through our JavaScript Class Tutorial first.

Declare Class in TypeScript

sum of 2 and 3 is 5


  class Sum{
    x:number=2;
    y:number=3;

    getSum(){`sum of ${this.x} and ${this.y} is ${this.x+this.y}`}

  }

  // create instance
  const sum=new Sum();
  console.log( sum.getSum() );
    

Class with constructor

To pass x any y dynamically, we can use constructor function in class.

sum of 4 and 5 is 9


  class Sum{
    x:number;
    y:number;

    constructor(x:number=0,y:number=0){
      this.x=x;
      this.y=y;
    }

    getSum(){`sum of ${this.x} and ${this.y} is ${this.x+this.y}`}

  }

  const sum=new Sum(4,5);
  console.log( sum.getSum() );
    

Public and Private Access Modifier

The above code is net and clean, but is verbose. We have to write too much line of code. To do this using lesser syntax, we can use Access Modifiers, i.e Public and Private in TypeScript.

By default x and y in above examples are public. We can change x and y data in constructor object as they are public.

Public

sum of 4 and 5 is 9


  class Sum{

    x:number;       // public
    y:number;       // public

    constructor(x:number=0,y:number=0){
    }

    getSum(){`sum of ${this.x} and ${this.y} is ${this.x+this.y}`}

  }

  const sum=new Sum(4,5);
  console.log( sum.getSum() );
    

Public Example in constructor

This is the recommended code in typescript with less code and better understanding. It is also one of the best feature of TypeScript.

sum of 4 and 5 is 9


  class Sum{

    constructor(public x:number=0, public y:number=0){ }

    getSum(){`sum of ${this.x} and ${this.y} is ${this.x+this.y}`}

  }

  const sum=new Sum(4,5);
  console.log( sum.getSum() );

Private fields

This is the recommended code in typescript with less code and better understanding. It is also one of the best feature of TypeScript.

2

Property 'pi' is private and only accessible within class 'Area'


  class Area{
    private pi:number=3.14; // private
    r:number=2;             // public
  }

  const area=new Area();

  console.log(area.r );       

  console.log(area.pi );