a blog for those who code

Monday, 1 May 2017

TypeScript Tutorial

In this post we will be learning about TypeScript by going through the basics of TypeScript. TypeScript is a free and open source programming language which lets you write JavaScript in a well defined way.

TypeScript is needed to add key concepts like classes, modules, interfaces etc which lack in JavaScript. These concepts are needed when you are building large applications because its very hard to maintain large code bases written in JavaScript. TypeScript can be defined as a typed super-set of JavaScript thus when TypeScript complies it gives us plain JavaScript.

Install TypeScript

The easiest way to install TypeScript is to use NPM (Node Package Manager). If you are not familiar with NPM, first go through Getting Started with Node Package Manager. To install typescript you need to run the below command :

npm install -g typescript

ALSO READ : TypeScript development in Visual Studio

Compilation of TypeScript Files

TypeScript is written in .ts files and need to be translated to JavaScript file. If you are using a command line then you can use command line tool called tsc (TypeScript Compiler) which converts the TypeScript file (filename.ts) to JavaScript file (filename.js).

tsc filename.ts

We can also use Gulp which is a task runner which will compile all TypeScript files to a JavaScript files. You will need to use Gulp-TypeScript module which is a typescript compiler for gulp with incremental compilation support, error reporting, different output streams for .js, .d.ts files etc.

Basic Types in TypeScript

The built-in types in TypeScript are 'number''boolean''string'. A very distinctive feature of Typescript is the support of Static Typing. Static Typing means that when you are declaring a variable you will also declare the type of a variable and the compiler in the compile time will make sure that wrong types of values are not assigned to that variable. For example :


You also have 'any' and 'void' data types in TypeScript. 'Any' is used to assign any values to it whereas 'void' is used for function return type to represent non-returning function. 'Void' data type can be seen as a sub-type of the 'Any' type and also a super-type of the 'Null' and 'Undefined' types.


Operators in TypeScript

The major operators in TypeScript are :

1. Arithmetic Operators ( +, -, *, /,  %, ++, --)
2. Logical Operators (&&, ||, !)
3. Relational Operators (>, >=, <, <=,  ==, !=)
4. Bitwise Operators (&, |, ^, ~, <<, >>)
5. Assignment Operators (=, +=, -=, *=, /=)
6. Conditional Operators ( ?: )
7. Type Operator ( typeOf )

Decision Making in TypeScript

Decision Making or Conditional Statement can be achieved using below ways :

1. if statement
2. if...else statement
3. switch statement

Iterators in TypeScript

Looping means running a block of code several times which can be achieved in TypeScript in the below ways :

1. for..in loop (Returns the list of keys of the object being iterated)
2. for..of loop (Retruns the list of values of the numeric properties of the object being iterated)

let arr = [1, 2, 3];

for (let i in arr) {
  console.log(i); // gives 0, 1, 2
}
for(let i of arr) {
  console.log(i) // gives 1, 2, 3
}


Functions in TypeScript

There are mainly four ways how you can define a function in TypeScript and they are :

1. Named Functions - It is similar to JavaScript function but here you have a type on the parameter passed.
2. Anonymous Functions - It is similar to Named Functions but without any name.
3. Lambda Functions - var square = (a : number) => a * a;
4. Class Functions - You need not have to write keyword 'function' before the function.

ALSO READ : Functions in TypeScript In Detail

Classes in TypeScript

Classes helps you to organize your code by organizing fields, properties, functions etc as shown below :
class Sports {
  sportName: string; //This is a field or variable
     //Constructor of class
    constructor(name: string) {
      this.sportName = name;
    }
    // Class Function
    loveSport() {
      return "I love playing " + this.sportName;
    }
}
// Creating new object of the class
var sports = new Sports("Cricket");

The Compiled JS File
var Sports = (function () {
  function Sports(name) {
      this.sportName = name;
  }
  Sports.prototype.loveSport = function () {
      return "I love playing " + this.sportName;
  };
  return Sports;
})();
var sports = new Sports("Cricket");


Inheritance in TypeScript

TypeScript supports an inheritance model (similar to object-oriented languages) which means that when a class of objects is defined, any subclass or derived class that is defined can inherit the definitions of one or more general classes. 

class Sports {
    private _name : string;
    constructor(name:string){
      this._name = name;
    }
}
//To create a subclass we use extends, A class can only extend one class
class Cricket extends Sports {
    constructor(name:string){
       // To call the base class member we use super
       super(name);
    }
}


Interfaces in TypeScript

Interface will help you to drive consistency across a set of classes which is a compile time approach used to standardization your code structure as shown below



Please Like and Share the Blog, if you find it interesting and helpful.

No comments:

Post a Comment