-->

Learn TypeScript Step By Step



Introduction

Today We will learn about TypeScript. We will see what is typescript, why we should learn TypeScript, how we can write code in typescript and more.

What is TypeScript?

TypeScript is an extension (a “superset”) of the JavaScript language. It allows us to write code in Object Oriented Design approach which makes possible writing JavaScript code faster and error-free with the help of type system provided in the TypeScript.

Do we really need to learn TypeScript?

Technically, you do not need to learn TypeScript and as at the end it's compiled into javascript code we can directly write javascript code Right? But it primarily provides optional static typing, classes, and interfaces which make it possible to write error free code and easier to organize the code base for very large application.

Also, I would like to mention 1 thing here is Angular 2 application is also written in TypeScript which is very popular client-side framework nowadays so we developers should learn this language.

It's special helps us to write javascript code, who are coming from strongly typed language like C# or Java as it follows OOP pattern.

let's start understanding practically.

Setup TypeScript development environment.

If you have Visual Studio 2013/2015  already installed then TypeScript will already be available and you can use Visual Studio IDE for this tutorial. But here I will use VS (Visual Studio) Code editor because of it is cross-platform (Linux, Mac OS, Windows) editor and can be extended with plugins to our needs.

Also, front-end developers, those are only working on client-side languages like HTML, CSS, javascript, jquery, angular etc. might not want to install Visual Studio IDE which comes with full feature.

1. Node.js 
First of all, we have to install Node.js for installing TypeScript. We can download Node.js from here: https://nodejs.org/en/download/

2. TypeScript 
After that, we will open Node.js command prompt for installing typescript and we will run > npm install -g typescript. here -g for global.

3. VS (Visual studio) Code editor
Now we will download and install VS Code editor. You can download VS Code editor from here https://code.visualstudio.com/download

We have done TypeScript development environment.

Let's open VS Code editor and create a simple HTML and a typescript file for learn TypeScript step be steps.

Learn about TypeScript supported types.

TypeScript allows us to declare variables with a specific data type which help us to avoid errors. It supports data types like string, number, boolean etc.

Now let's see how we can declare a variable of a specific datatype in typescript and how it helps us to write error free code.

First of all, I will create a folder (empty folder) where we create our project files.

Now I will open the folder in VS Code editor. So open VS Code Editor > Go to file menu from VS code editor for open the folder > click on Open Folder > select the project folder what we have just created.

Now we will add a TypeScript file here in this folder. For creating a new file click on the "New file" icon from VS Code editor (see below image) > Enter file name. Here I have created a file "datatypes.ts".


Before writing typescript code in the file, I will write a javascript function for add 2 values then we will type the same function in typescript for understanding how TypeScript type system help us to write error free code.

TypeScript is a superset of javascript. So we can write any javascript in TypeScript file. Let's write a function for adding 2 value in javascript code first.
//Javascript 
function Add(val1, val2){
     return val1 + val2;
 }
alert(Add(2,5));

Let's create a Html file here in this folder so we can run and check the code working fine or not.

<html>
    <head>
        <title>TypeScript Tutorial</title>
        <script src="./datatypes.js"></script>
    </head>
    <body>
        
    </body>
</html>

You can see here in the line no. 4, I have added datatypes.js file reference whereas we have datatypes.ts file in our project folder. Right?

We can not directly use TypeScript file in the browser because today browsers not supported typescript file. So we will use TypeScript transpiler that converts our Typescript code to javascript code so we can use it in today browsers.

For converting the typescript file into javascript file we have to use TypeScript transpiler. So open integrated terminal  from View > Integrated Terminal from VS Code editor > write command "tsc datatypes.ts" and then hit the enter button.

Here tsc is TypeScript transpiler and datatypes.ts is out typescript file.

you can see that now the datatypes.js file is generated.

Let's run the index.html file in the browser.


Right click on the index.html file from sidebar > click on copy path > Open your browser and paste the path in the address bar and hit the enter button.

You can see It's showing 7 in the alert box.

Now we update the code as below, it will show 2sourav in the alert box which is not valid.

//Javascript 
function Add(val1, val2){
     return val1 + val2;
 }
alert(Add(2,'sourav'));

Let's write the same function in TypeScript
function Add(val1:number, val2:number){
    return val1 + val2;
}
alert(Add(2,5));

You can see here in the 1st line we have added parameters with :number that means it's a number type variable and we can not pass another type value when we will call the add function. If we do that, TypeScript compiler will show an error message here. So in this way TypeScript help us to write error free code.

TypeScript allows us to declare variables with a specific type. Here in the below code, you can see how we can declare a variable of a specific type.
var IsDone:boolean = false;
var Name: string = "Sourav";
var Salary: number = 12345;
var numberArray:Array<number> = [1,2,3,4];

Learn about TypeScript interface

Now the question is what is Interface? why and when we will use this?

An interface is a set of properties and or methods that an entity should conform to.
To understand Interfaces, let me start with a simple example to make it easier to grab the concept and also how its help us to write error free code.

Suppose we have to create a function for showing user details in javascript.
function ShowUserDetails(user){
   alert("Name " + user.FirstName + ", age :" + user.Age);
}
var obj = {FirstName: 'Sourav'};
ShowUserDetails(obj);

If you run the code in the browser you will see that the alert message is showing "undefined". We should not write code like this right? But it's not giving us any warning/error message at all. What if we get an error message at compile time? We could resolve the issue. That's the benefit of using TypeScripts. Let's see in action.

Now I will update the code in TypeScript.
interface Iperson{
    FirstName:string,
    LastName:string,
    Age: number,
    ContactNo? : string
}

function ShowUser(user:Iperson){
    alert("Name :" + user.FirstName + ", Age : " + user.Age);
}

var user:Iperson = {
    FirstName : "Sourav",
    LastName:"Mondal",
    Age:28
};
ShowUser(user);

Here I have created an Interface Iperson with the interface keyword in typescript and you can I have created a function for showing user details with a parameter of Iperson type.

Now if we run the example code you can see all are working as aspected and if you try to call the function ShowUser without assigning mandatory fields of the Iperson interface, it will show 1 error message at the compile time. So this way TypeScripe help us to write error free code. Here you should notice that I have added a property ContactNo with a "?" mark, that means it's a not mandatory property.

TypeScript Class

Let's start with one of the most important features in TypeScript is Class.

If you are coming from strongly typed languages like C# or Java, you are probably aware of the benefit of using classes. Classes make it easy to group related variables and functions into a container which helps us to re-use code and easy to organize the code base for very large application.

Let's create a class and re-use it.
For creating a class in typescript we have to use class keyword followed by the class name.
class User{
    FirstName:string;
    LastName: string;
    ContactNo:string;    

    ShowUserDetails(){        
        let message:string = `Name : ${this.FirstName} ${this.LastName}, Contact No : ${this.ContactNo}`;
        alert(message);
    }
}

let meAsUser = new User();
meAsUser.FirstName = "Sourav";
meAsUser.LastName = "Mondal";
meAsUser.ContactNo = "1234567890";
meAsUser.ShowUserDetails(); 

Here I have created a class User with this 3 fields and a function. As I have not defined any access modifier all are public because in TypeScript public is the default access modifier.

You can that in line 12, I have created an instance (object) of the class using new keyword followed by the class name. Here in line 13-16 I have assigned fields value and called the function for showing user details.
you can see that I have used backtick(`), this is called template strings in typescript, which can span multiple lines and have embedded expressions.

Class Constructor

What is Constructor?
The constructor is a special function of a class which is called when we create an object of that class.

Why & when this is required?

Let's see in practical. If we remove the 3 lines where we have assigned fields value and then call the function for showing user details, what we can see that it will show the alert box but message with undefined values.

class User{
    FirstName:string;
    LastName: string;
    ContactNo:string;    

    ShowUserDetails(){        
        let message:string = `Name : ${this.FirstName} ${this.LastName}, Contact No : ${this.ContactNo}`;
        alert(message);
    }
}

let meAsUser = new User();
meAsUser.FirstName = "Sourav";
meAsUser.LastName = "Mondal";
meAsUser.ContactNo = "1234567890";
meAsUser.ShowUserDetails(); 

This function ShowUserDetails() should not be called before assign fields value. So it will be nice if we can assign the value of the variables when we will create an object of the class. we can do this with the help of constructor. Let's see. 
class User{
    FirstName:string;
    LastName: string;
    ContactNo:string;
    private BankBalance:number;
    protected pro1:number;
    constructor(firstName:string, lastName:string, contactNo:string){
        this.FirstName = firstName;
        this.LastName = lastName;
        this.ContactNo = contactNo;
    }
    ShowUserDetails(){
        
        let message:string = `Name : ${this.FirstName} ${this.LastName}, Contact No : ${this.ContactNo}`;
        alert(message);
    }
}

let meAsUser = new User("Sourav","Mondal","234567890");
// meAsUser.FirstName = "Sourav";
// meAsUser.LastName = "Mondal";
// meAsUser.ContactNo = "1234567890";
//meAsUser.ShowUserDetails();

In this way, we can use the class constructor for initializing the variables of the class.

Inheritance in TypeScript

As I have just told you that I will show you how we can re-use code. Let's start with Inheritance which is an another important features of TypeScript which enable us to reuse code.

In object-oriented programming, inheritance enables new objects to take on the properties of existing objects. A class that is used as the basis for inheritance is called a superclass or base class. A class that inherits from a superclass is called a subclass or derived class.
A child inherits visible properties and methods from its parent while adding additional properties and methods of its own.

Let's create a class where we will inherit visible properties of User class that we have just created in the above section.
class Employee extends User{    
    Designation:string;
    JoiningDate:string;
    constructor(firstName:string, lastName:string, contactNo:string, 
                designation:string, joiningDate:string){
        super(firstName,lastName,contactNo);
        this.Designation = designation;
        this.JoiningDate = joiningDate; 
    }
    
    ShowEmployeeDetails():void{
        let message:string = `Employee Name : ${this.FirstName} ${this.LastName}, Designation : ${this.Designation}`;
        alert(message);
    }
}

let meSoftwareDeveloper = new Employee("Sourav","Mondal","123456789","Software Developer","1st may 2010");
meSoftwareDeveloper.ShowEmployeeDetails();


You can see here I have created a new class Employee where I have inherited User class using extends keyword.  Now all the visible fields (public & protected fields are visible in the child class) are inherited here in the Employee class. This way we can reuse code in TypeScript.

Access Modifiers

Access modifiers control the accessibility of the members of a class.
You can see in the previous example where we have inherited User class in the Employee class, all the fields of User class are accessible in the Employee class and this is because of we have not defined any access modifier which makes those fields public fields as public is default access modifier in TypeScript.

Suppose we don't want a field defined in the User class to access outside of the class itself or even in the child class, So how we can do that? we can do that with the help of access modifiers. Let's update User class with adding 2 new fields.
class User{
    FirstName:string;
    LastName: string;
    ContactNo:string;
    private BankBalance:number;
    protected pro1:number;
    constructor(firstName:string, lastName:string, contactNo:string){
        this.FirstName = firstName;
        this.LastName = lastName;
        this.ContactNo = contactNo;
    }
    ShowUserDetails(){
        
        let message:string = `Name : ${this.FirstName} ${this.LastName}, Contact No : ${this.ContactNo}`;
        alert(message);
    }
}

let meAsUser = new User("Sourav","Mondal","234567890");

Now if we try to access the field BankBalance from Employee class or anywhere outside of the user class, we can not access the field and compiler will throw an error message that we can not access the field. But we can access the pro1 field from Employee class as it's a child class of the User class but the field can not accessible outside of the User & Employee class.

Download

Hello ! My name is Sourav Mondal. I am a software developer working in Microsoft .NET technologies since 2010.

I like to share my working experience, research and knowledge through my site.

I love developing applications in Microsoft Technologies including Asp.Net webforms, mvc, winforms, c#.net, sql server, entity framework, Ajax, Jquery, web api, web service and more.