TypeScript - KickStart | Brain Mentors Skip to content

TypeScript – KickStart

What is TypeScript?

TypeScript (JavaScript that scale) – Develop by Microsoft.
It is a superset or Wrapper of J.S and compile it into JS. The TypeScript (T.S) canʼt run on any browser. It Provides Strongly Typed, Generics, Interfaces, Modular.

Now, we know that TypeScript doesn’t run on any browser.So,How will TypeScript get executed?

TypeScript Flow

TypeScript is Get Converted into JavaScript at the End by TypeScript Compiler

Now , Its Time to Setup Typescript

  • Must have Node JS in Your Machine
  • check Node js and npm in your machine e.g node -v , npm -v
  • npm install typescript -g (Install TypeScript)

Now, Lets get Started with TypeScript

Now, we will start by running first example of TypeScript i.e.., Compile TS into JS

tsc <Typescript File Name>

We can also compile multiple TypeScript files in single shot using following command :

tsc <fileName>.ts <Folder/ <Filename>.ts>

tsc —init
this will generate tsc.config.json file

tsc
-now this command search for tsconfig.json file for ts related configuration
After this u need to run tsc command only

Now , Letʼs Start the Types Basics

There are 2 types of types in TypeScript :

a) Implicit Types

let a = 100;
a=“brain mentors” ; // generate error

b) Explicit Types

1. Basic Types (string , number, boolean,any)

e.g.
let name = “Brain Mentors Pvt
Ltd”;
name = 11; // this will generate error in typescript

DEFINE STRING TYPE
var name:string=“Amit Srivastava”;

DEFINE NUMBER TYPE
var age:number = 21;

DEFINE BOOLEAN TYPE

var attend:boolean = true;

DEFINE ANY TYPE , THIS CAN TAKE ANYTHING

var e:any=100;

2. Array Types

var arr:string[] = [“Amit”,”Brain Mentors”];

3. Define Tuples – It is like an array but mix of types.

var records:[string,number] = [“Amit”,1001]; // It is a normal array
var rows = [];
rows[0] = records;
rows[1] = records2;
rows[2] = records3;

4. Define Enums – To make numeric values more expressive.

enum Days {
SUNDAY=1,MONDAY=2,TUESDAY
}

var day:Days = Days.SUNDAY;
switch(day){
case SUNDAY:
case MONDAY:
}

Example:
enum Week
{SUNDAY=1,MONDAY,Tuesday};
let d:Week = Week.MONDAY;

console.log(“Week “+d);
if(Week[“SUNDAY”]==0){ console.log(“Sunday”); }
if(Week.SUNDAY==0){ console.log(“Sun”);}

Note: Default enum start with 0

5. Using Types in Function

function add(x:number,y:number):number
{
return x + y;
}

6. Using Function as Type

var fn: (x:number,y:number)=>number ;

example
var d1 :
(a:number,b:number)=>number;
function add(x:number,y:number):number{
return x + y;
}
function
sub(x:number,y:number):void{
console.log(“Add “+(x+y));
}
d1 = add;
console.log(d1(1000,2000));
d1= sub;
console.log(d1(10,20));

7. Object as a Type

type mytype = {x:number,y:number};
var e : mytype= {x:100,y:200}
var e1 :mytype;

var x:number = 100;
var x:number = 100;
var obj:{name:string,age:number,salary:number} = {“Amit”, 21,9999}; // JS
var obj :{name:string,age:number} ={“Amit”,21}; //TS

-Using Alias name for Object Type

type objectType =
{
id:number,name:string,address:string[]
}
var obj:objectType =
{
id:1001,name:ʼAmitʼ,address:[“Delhi”]
}

var e:objectType

8. Union Type

var w:undefined|null|0;
var age:number|string ;
// Now this will take number or string age=21 or age=“21”

never type (TS 2.0) – When your function suppose to return error always, it never return the value

function iwIllNeverFinish():never
{
throw new Error(“This Transaction Never Complete Due to Some Error on Server Side “);
}

nullable type (TS 2.0) – this is the configuration to treat null types only for the object.

Sample tsconfig.json

SOME USEFUL FLAGS FOR TSCONFIG.JSON

// Solution is add entry in tsconfig.json (“strictNullChecks”:true)

// tsconfig.json “noEmitOnError”: true, Force TypeScript not to generate JS if TS has any error

// “sourceMap”” : true (Create Bridge file b/w ts and js so we can debug ts in chrome)

// “noImplicitAny”: true , now u need to define type any , if u need specify any data type

// “noUnusedLocals”: true, Local Variable must be initalize before use,

// “noUnusedParameters”: true, for unused function paramters

Defining Class in TS

Creating Class
class Employee
{
private static autoNumber:number=10; // Defining private (scope is limited to the class), static bind with class
private id:number;
public name:string; //default is public
salary:number; // I am public by default
protected designation:string; // use by child class
constructor(name:string, public companyName:string)
{
this.name = name;
this.id = Employee.autoNumber++;
}
public print():void
{
console.log(Id is ${this.id} and Name is ${this.name} and Company Name is ${this.companyName});
}
}
var ram = new Employee(“Amit”,”Brain Mentors“);
ram.print();

Define Setter and Getter Example

class A
{
private _id:number;
constructor(id:number)
{
this._id = id;
}
set id(i:number)
{
this._id = i;
}

get id():number
{
return this._id;
}

}

var a:A = new A(100);
a.id = 1001;
console.log(“Id is ::: “,a.id);

Inheritance in TypeScript


Abstract class act like a most generic class and it is used for inheritance and we canʼt create an object of Abstract class.

abstract class Banking
{
constructor()
{
}
abstract show():void;
}
Extends is used for inheritance
class Account extends Banking
{
constructor(protected accountid:number, private accountname:string,public balance:number)
{
super(); // Calling parent class constructor
}
show():void
{
console.log(“Define Abstract method…”);
}
}
class SavingAccount extends Account{
private _roi:number;
constructor(accid:number, private type:string, balance:number){
super(accid,”Saving”,balance);
}
printDetails():void{
console.log(Id is $ {this.accountid} Name is $ {this.balance});
console.log(Type is ${this.type} );
}

Static – Static bind with the class name, this will come in the memory when you load a class.
So you can access them with ClassName.StaticMember, No need to create an object of the class.
class W{
static a:number=10;
static print():void{
console.log(“A is “+a);
}
}
W.print();

Sign Up and Start Learning