Post2

Introduction to TypeScript

Posted by Devendra Pratap Singh

What is TypeScript?

TypeScript is not a Framework but a programming language that helps in developing a JS framework. It is a superscript for JavaScript, which means you can even write JavaScript code in TypeScript. Being a programming language, TypeScript provides a modular approach to writing codes. The TypeScript code is compiled to plain JavaScript, just as the C# code is compiled to DLLs. This means you can rename any valid .js file to .ts and compile it with other TypeScript files.

Also, TypeScript is an object oriented language, thus, it supports classes, interfaces, inheritance, modules, besides type-safety and different data types such as number, string, Boolean, void, null, and undefined.

TypeScripts are never executed by browser, which means you do not need to add reference of TypeScript file; instead adding a reference to compiled .js file would be enough.

Being a superscript of JavaScript, TypeScript has helped develop some very popular JavaScript frameworks including:

  • AngularJS
  • Dojo
  • ZoomCharts
  • Ionic
  • BabylonJS
  • Sitepen
  • InstartLogic

Why Use TypeScript?

Advantages of TypeScript

  • It is difficult to debug JavaScript code but TypeScript provides simple way to debug and read it.
  • JavaScript is not type-safe but TypeScript is a type-safe language and provides type safety at compile time.
  • JavaScript does not provide any direct way to create classes while in TypeScript we can easily create classes, interfaces etc.
  • Supports latest standard and evolving features of JavaScript including ES5 and ES6.
  • Supports modularity.

Installing TypeScript

You can install TypeScript through any of the following ways:

  • Using npm command in Node JS package manager
  • Installing TypeScript Visual Studio plugin: – TypeScript comes embedded with Visual Studio 2017 but for Visual Studio 2015, user’s need to install Update 3, while those using Visual Studio 2013 need to install Update 2.

Step-by-Step Integration of TypeScript in a Visual Studio Project

  • Create a Project using Visual Studio
  • Right-click on the folder where you want to add the TypeScript file and select new item from the menu
  • Select Web from left hand side of the opened window
  • Select TypeScript file from the right side of the window
  • Enter a suitable name for the TypeScript file
  • Click on Add button
  • A file will be created inside the selected folder with the provided name

Step to Create TypeScript HTML Project in a Visual Studio Project

  • Click on File menu then navigate to item-> New -> Project
  • On the left pane of the Project window select TypeScript
  • From the right pane select HTML Application with TypeScript

  • Enter a name for the File and select the location to save the Project
  • Click OK

How to Add Typescript file

To add a new TypeScript right-click on the scripts folder and click New Item. Then choose TypeScript File and type an appropriate name for the file.

Access Modifiers

In TypeScript there are three types of Access Modifiers:-

Public Class members including variable, properties, and methods declared public can be accessed outside the class it is declared. By default every member is public.
Private Class members are declared as private when their scope needs to be restricted to within the class.
Protected Class members are declared as protected when their scope needs to be extended to classes which inherit the class. Thus, the protected members are limited to only that class and its sub class.

Readonly Modifier

Readonly is a special modifier that’s used to assign values to variables either at the time of declaration or in the constructor of that class. To declare the readonly property of a member in TypeScript, you need to use the readonly keyword. The attempt to assign values somewhere else, will result in exception.

 

class Company {

readonly Country: string = “India”;

readonly CompanyName: string;

constructor(name: string) {

this.CompanyName = name;

}

ShowDetails() {

console.log(this.CompanyName + “: “+ this. Country);

}

}

 

let comp = new Company(“Xavient”);

comp.ShowDetails (); // Xavient : India

comp.CompanyName = “TCS”; //Error, Company name can be initialized only within constructor

 

Variable Declarations

In JavaScript there is only one way to declare variables but in TypeScript you can use two more keywords let and const to declare variables.

Type Description
Any Type To declare a variable which can hold data of any type, use Any keyword. The Any type is a super type of all types, which can represent any JavaScript value. You can assign any type of value to the keyword, ranging from number to string.
Number In TypeScript the Number keyword is used to define number type variable. TypeScript supports decimal, hexadecimal, binary, and octal literals. For Example:-

let Age: number = 24;

Boolean To define and declare a variable Boolean in TypeScript, Boolean keyword is used.  For example:- let IsFlag : Boolean = false;
String The string keyword is used to declare and define string type in TypeScript. For example:- let name: string = ”Xavient Information System”;
Enum The Enum keyword is used to define a set of related named constants, similar to C#. By default, the set will start from 0 but developers are free to set any value. For example:-

 

Default Value: –      0             1             2             3             4             5             6

Enum WeekDays { Monday, Tuesday,  Wednesday, Thursday, Friday, Saturday, Sunday};

 

Custom Value: –      2             3             4             5             6             7             8

Enum WeekDays { Monday, Tuesday,  Wednesday, Thursday, Friday, Saturday, Sunday};

Object Types

Array

In TypeScript an Array can store multiple values of same type. You can define array type using [] bracket followed by type. For example:-

let sequenceNumber: number[]=[1,2,3,4,5,6,7,8,9]

OR,

let sequenceNumber: Array<number>=[1,2,3,4,5,6,7,8,9]

 

Tuple

Tuple type is used to define an array where the elements can be of different type. For example:-

let EmployeDetails: [string, string, number];

EmployeDetails = [“Devendra”, “Xavient”, 4];

 

Function

In TypeScript we can create both named and anonymous functions. For example:-

//named function with number as return type

function addTwoNumber(num1: number, num2: number): number {

return num1 + num2;

}

//anonymous function with number as return type

let sum = function (num1: number, num2: number): number {

return num1 + num2;

};

 

Class

As in C#, you can create a class in TypeScript with class keyword. The class keyword is followed by the class name. A class definition can include fields, constructors, and functions.

class Employee {

EmployeeID: number;

EmployeeName: string;

Designation: string;

constructor(employeeID: number, employeName: string, designation: string) {

this.EmployeeID = employeeID;

this.EmployeName = employeName;

this.Designation = designation;

}

ShowEmployeeDetails() {

return this.EmployeeID + “ ” + this.EmployeName + “ ” + this.Designation;

}

}

 

Creating Instance of class

You can create instances of the class in TypeScript with the new keyword

var EmplyeeDetails = new Employee (“11111”,”Devendra”,”SSE”)

Reading the value

let empName: string= EmplyeeDetails.EmployeName;

Conclusion

TypeScript is quite similar to JavaScript and since it is an object oriented language, it is quite similar to C# too. It is, therefore, very simple for college grads and professionals to learn and adopt, presuming they have a bit of coding background. The article just covers the basics of TypeScript, if you wish to learn more, you may explore some of the advanced concepts mentioned below:

  • Dynamic Import Expressions
  • Improved inference for generics
  • Type parameter inference from contextual types
  • Return types as inference targets
  • Stricter checking for generic functions
  • Strict contra variance for callback parameters
  • Template strings

That’s all from us folks! Comment below and let us know if you relate!

Until next time!

Related Posts

  • ReactJS JavaScript FrameworkReactJS JavaScript Framework

    What is ReactJS? ReactJS is a front-end library developed by a collaboration of Facebook and Instagram. It enables users to create interactive, stateful, and reusable UI components. In 2003, Facebook…

  • DevOps: In a NutshellDevOps: In a Nutshell

    DevOps is quite a buzzword nowadays. Organizations have formulated a definition for it and have implemented it accordingly. With a perspective of their own, organizations tend to think they have…

  • ChatBots (Part 2) – How to make BotsChatBots (Part 2) – How to make Bots

    “It is said that to explain is to explain away. This maxim is nowhere so well fulfilled as in the area of computer programming, especially in what is called heuristic…

  • Mobile App Automation Testing using ‘ESPRESSO’

    If you are a Mobile Apps Test Engineer, you cannot overlook the very reliable Google Product i.e. Espresso. Espresso is an automatic UI testing or as we call it “hands…

  • KAFKA-Druid Integration with Ingestion DIP Real Time Data

    The following blog explains how we can leverage the power of Druid to ingest the DIP data into Druid (a high performance, column oriented, distributed data store), via Kafka Tranquility…

  • Introduction to Microservices

    Traditional development methodologies encourage the ‘monolithic’ approach to application development. Building a single application that does everything required has been the modus operandi for a while. However, with the rise…

Leave a Reply

Your email address will not be published. Required fields are marked *