TypeScript

A Quick guide for Typescript

A Quick guide for Typescript

What is Typescript?

TypeScript is a superset of JavaScript which primarily provides optional static typing, classes and interfaces. One of the big benefits is to enable IDEs to provide a richer environment for spotting common errors as you type the code.

Typescript was first made public in October 2012 (at version 0.8), after two years of internal development at Microsoft.

TypeScript 0.9, released in 2013, added support for generics

TypeScript 1.0 was released in 2014.

In September 22, 2016, TypeScript 2.0 was released and it introduced several features, including the ability for programmers to optionally prevent variables from being assigned null values.

Typescript Features

TypeScript adds features to ECMAScript 5

Additional features include:

  • Type annotations and compile-time type checking
  • Type inference
  • Type erasure
  • Interfaces
  • Enumerated type
  • Mixin
  • Generic
  • Namespaces
  • Tuple
  • Await

The following features are back-ported from ECMAScript 2015:

  • Classes
  • Modules
  • Abbreviated “arrow” syntax for anonymous functions
  • Optional parameters and default parameters

Basic data types in Typescript

Basically typescript has the same datatype as JavaScript, with a convenient enumeration type.

Data type

Syntax

Boolean

 let isDone: boolean = false;

String

 let customerName: string= "Samuel Jackson";

Number

 let price: number = 19.95;

Date

 let orderDate: Date = new Date(2017, 2, 9);

 Any

 let notSure: any = 4;
 notSure = "maybe a string instead";
 notSure = false; // okay, definitely a boolean --

Enum

 enum Color {Red, Green, Blue};
 let c: Color = Color.Green;

Array

 let cards: string[] = ['ICICI', 'AXIS', 'PNB', 'SBI', 'OTHER'];

 Null

 let orderId: number = null;

 Undefined

 let u: undefined = undefined;

 Tuple

 let orderDetail: [number, string,];  //Tuple declaration
 orderDetail: [101, Nike Shoes,];     //Tuple Initialization

Void

 function warnUser():  void {
        alert("This is my warning message"); }

Const

 const lives: number = 99;

TypeScript Classes

Lets have a look at a simple class example in Typescript.

[pastacode lang=”javascript” manual=”class%20Greeter%20%7B%0A%20%20%20%20greeting%3A%20string%3B%0A%20%20%20%20constructor(message%3A%20string)%20%7B%0A%20%20%20%20%20%20%20%20this.greeting%20%3D%20message%3B%0A%20%20%20%20%7D%0A%20%20%20%20greet()%20%7B%0A%20%20%20%20%20%20%20%20return%20%22Hello%2C%20%22%20%2B%20this.greeting%3B%0A%20%20%20%20%7D%0A%7D%0A%0Alet%20greeter%20%3D%20new%20Greeter(%22world%22)%3B” message=”A class in Typescript” highlight=”” provider=”manual”/]

Here we declare a new class Greeter. This class has three members: a property called greeting, a constructor, and a method greet.

when we refer to one of the members of the class we prep-end this.. It donates that it’s a member access.

In the last line we construct an instance of the Greeter class using new. This calls into the constructor we defined earlier, creating a new object with the Greeter shape, and running the constructor to initialize it.


Inheritance in Typescript

One of the most fundamental patterns in class based programming is to extend existing class to create new class using inheritance.

Let’s see an example of Inheritance in Typescript

[pastacode lang=”javascript” manual=”class%20Animal%20%7B%0A%20%20%20%20name%3A%20string%3B%0A%20%20%20%20constructor(theName%3A%20string)%20%7B%20this.name%20%3D%20theName%3B%20%7D%0A%20%20%20%20move(distanceInMeters%3A%20number%20%3D%200)%20%7B%0A%20%20%20%20%20%20%20%20console.log(%60%24%7Bthis.name%7D%20moved%20%24%7BdistanceInMeters%7Dm.%60)%3B%0A%20%20%20%20%7D%0A%7D%0A%0Aclass%20Snake%20extends%20Animal%20%7B%0A%20%20%20%20constructor(name%3A%20string)%20%7B%20super(name)%3B%20%7D%0A%20%20%20%20move(distanceInMeters%20%3D%205)%20%7B%0A%20%20%20%20%20%20%20%20console.log(%22Slithering…%22)%3B%0A%20%20%20%20%20%20%20%20super.move(distanceInMeters)%3B%0A%20%20%20%20%7D%0A%7D%0A%0Aclass%20Horse%20extends%20Animal%20%7B%0A%20%20%20%20constructor(name%3A%20string)%20%7B%20super(name)%3B%20%7D%0A%20%20%20%20move(distanceInMeters%20%3D%2045)%20%7B%0A%20%20%20%20%20%20%20%20console.log(%22Galloping…%22)%3B%0A%20%20%20%20%20%20%20%20super.move(distanceInMeters)%3B%0A%20%20%20%20%7D%0A%7D%0A%0Alet%20sam%20%3D%20new%20Snake(%22Sammy%20the%20Python%22)%3B%0Alet%20tom%3A%20Animal%20%3D%20new%20Horse(%22Tommy%20the%20Palomino%22)%3B%0A%0Asam.move()%3B%0Atom.move(34)%3B” message=”Example of Inheritance in Typescript” highlight=”” provider=”manual”/]

In the above example,

The extends keywords used to create a subclass. Here Horse and Snake are subclass of the base class Animal and got access to the properties of it.

To execute the constructor of the base class, Derived classes must call super().

The example also shows how to override methods in the base class with methods that are specialized for the subclass. Here both Snake and Horse create a move method that overrides the move from Animal, giving it functionality specific to each class. Note that even though tom is declared as an Animal, since its value is a Horse, when tom.move(34) calls the overriding method in Horse:

<code>Slithering...
Sammy the Python moved 5m.
Galloping...
Tommy the Palomino moved 34m.
</code>

Interface in Typescript

Interface contains only declaration of members. And derived class will define the members.

To understand it better, let’s take an object..

var person = { 
   FirstName:"John", 
   LastName:"Cenna", 
   sayHi: ()=>{ return "Hi"} 
};
If we see look at the declaration of the object, it could be...
{ 
   FirstName: string, 
   LastName: string, 
   sayHi()=>string 
}

To use this declaration across multiple objects, we will define it as an interface. Let’s see an example

[pastacode lang=”javascript” manual=”interface%20Person%20%7B%20%0A%20%20%20firstName%3Astring%2C%20%0A%20%20%20lastName%3Astring%2C%20%0A%20%20%20sayHi%3A%20()%3D%3Estring%20%0A%7D%20%0A%0Avar%20customer%3APerson%20%3D%20%7B%20%0A%20%20%20firstName%3A%22Tom%22%2C%0A%20%20%20lastName%3A%22Hanks%22%2C%20%0A%20%20%20sayHi%3A%20()%3Astring%20%3D%3E%7Breturn%20%22Hi%20there%22%7D%20%0A%7D%20%0A%0Aconsole.log(%22Customer%20Object%20%22)%20%0Aconsole.log(customer.firstName)%20%0Aconsole.log(customer.lastName)%20%0Aconsole.log(customer.sayHi())%20%20%0A%0Avar%20employee%3APerson%20%3D%20%7B%20%0A%20%20%20firstName%3A%22Jim%22%2C%0A%20%20%20lastName%3A%22Blakes%22%2C%20%0A%20%20%20sayHi%3A%20()%3Astring%20%3D%3E%7Breturn%20%22Hello!!!%22%7D%20%0A%7D%20%0A%20%20%0Aconsole.log(%22Employee%20%20Object%20%22)%20%0Aconsole.log(employee.firstName)%20%0Aconsole.log(employee.lastName)” message=”Interface in TypeScript” highlight=”” provider=”manual”/]

On compiling it will generate following JavaScript code:

[pastacode lang=”javascript” manual=”var%20customer%20%3D%20%7B%20firstName%3A%20%22Tom%22%2C%20lastName%3A%20%22Hanks%22%2C%0A%20%20%20sayHi%3A%20function%20()%20%7B%20return%20%22Hi%20there%22%3B%20%7D%0A%7D%3B%0Aconsole.log(%22Customer%20Object%20%22)%3B%0Aconsole.log(customer.firstName)%3B%0Aconsole.log(customer.lastName)%3B%0Aconsole.log(customer.sayHi())%3B%0Avar%20employee%20%3D%20%7B%20firstName%3A%20%22Jim%22%2C%20lastName%3A%20%22Blakes%22%2C%0A%20%20%20sayHi%3A%20function%20()%20%7B%20return%20%22Hello!!!%22%3B%20%7D%20%7D%3B%0A%0Aconsole.log(%22Employee%20%20Object%20%22)%3B%0Aconsole.log(employee.firstName)%3B%0Aconsole.log(employee.lastName)%3B” message=”JavaScript code after compiling the above TypeScript” highlight=”” provider=”manual”/]

Interfaces are not to be converted to JavaScript. It’s just part of TS. 

The output of the above code is :

Customer object 
Tom 
Hanks 
Hi there 
Employee  object 
Jim  
Blakes 
Hello!!!

Functions in TypecScript

Functions are building blocks for any application. Let’s see an example of Function :

[pastacode lang=”javascript” manual=”function%20disp_details(id%3Anumber%2Cname%3Astring%2Cmail_id%3F%3Astring)%20%7B%20%0A%20%20%20console.log(%22ID%3A%22%2C%20id)%3B%20%0A%20%20%20console.log(%22Name%22%2Cname)%3B%20%0A%20%20%20%0A%20%20%20if(mail_id!%3Dundefined)%20%20%0A%20%20%20console.log(%22Email%20Id%22%2Cmail_id)%3B%20%0A%7D%0Adisp_details(123%2C%22John%22)%3B%0Adisp_details(111%2C%22mary%22%2C%22mary%40xyz.com%22)%3B” message=”Function in TypeScript with optional parameter” highlight=”” provider=”manual”/]

In above code mail_id is an optional parameter, if we will not pass value to mail_id, it’s value is set undefined.

Output of the above code is:

ID:123 
Name John 
ID: 111 
Name  mary 
Email Id mary@xyz.com


Other resources to learn typescript in detail:

Microsoft -Handbook

OfficialTypeScript documentation

Leave a Reply