TypeScript Tutorial: Classes in TypeScript (Chapter 6)

With the introduction of ECMAScript 2015 JavaScript has got Classes as its first class citizens. Yes, you can use classes in JavaScript now (in most of the browsers). But what about people, who are still relying on the older browsers? The answer is TypeScript. When we compile a TypeScript, we can target it to use ECMAScript 5, where Classes in TypeScript are automatically converted to an equivalent prototype based declaration.

A TypeScript Tutorial for beginners on TypeScript

Classes in TypeScript

As a developer in Object Oriented Programming language, we know what a class is and what are the core characteristics of a class. TypeScript has adopted much, if not all the characteristics. We can define classes, which support prototype-based inheritance, super calls, instance and static methods and constructors. In this chapter we will be seeing and learning about the classes in TypeScript. Here is the sample of TypeScript and its compiled JavaScript (you have to leave the habit of seeing the compiled JavaScript, leave it only for the browsers to read).

class Person {
    firstName: string;
    lastName: string;
}

JavaScript Output

var Person = (function () {
    function Person() {
    }
    return Person;
}());

Constructors

We can define a constructor for classes in TypeScript by using keyword function constructor. This function is called and used whenever a new instance of the class is created. The above class can be defined with a constructor where it requires 2 parameters to initialize the properties of the class. Here is the snippet for the same.

class Person {
    firstName: string;
    lastName: string;

    // parameterized constructor
    constructor (fname: string, lname: string) {
        this.firstName = fname;
        this.lastName = lname;
    }
}

The only thing you will not get over here is the capabilities of having multiple constructors. But that functionality can be achieved by other means.

Access Modifiers

public, protected and private members in classes has their usual role in TypeScript language. By default every thing you declare in the classes, they are public and are accessible outside the class. But, still for the clarity and consistency if you want to explicitly declare a member public you can use the public keyword.

Actual use of protected members will be observed during the inheritance chapter. Here we will see the private members only as of now. Functions and Properties declared as private will be only accessible from within the class and can be used in performing the internal operations. Let’s see the below program which builds a Person and gets the full name.

class Person {
    private firstName: string;
    private lastName: string;
    private fullName: string;

    // parameterized constructor
    constructor (fname: string, lname: string) {
        this.firstName = fname;
        this.lastName = lname;
        this.buildFullName();
    }

    private buildFullName () {
        this.fullName = this.firstName + " " + this.lastName;
    }

    public getFullName(): string {
        return this.fullName;
    }
}

let person = new Person("John", "Doe");

console.log(person.getFullName());

Getter and Setter

Classes in TypeScript support getter and setter properties, which can be used to fine-grind the access to the properties of class. For example if we can rewrite the above code sample with the help of getters and setters as below.

class Person {
    private firstName: string;
    private lastName: string;
    private fullName: string;

    // parameterized constructor
    constructor (fname: string, lname: string) {
        this.firstName = fname;
        this.lastName = lname;
        this.buildFullName();
    }

    private buildFullName () {
        this.fullName = this.firstName + " " + this.lastName;
    }

    public get FullName(): string {
        return this.fullName;
    }
}

let person = new Person("John", "Doe");

console.log(person.FullName);

The only change you will observe is shown in the highlighted line. One more thing to point out there is that the getters and setters are only available when you are targeting your compiler to ES5 or above.

We will be talking about the abstraction and a few other aspects of the classes in TypeScript in upcoming chapter on Inheritance. There are many more things to be talked in this topic, but let’s keep that for some other day. I am hoping that you are enjoying these chapters on TypeScript and would like to read more everyday. I assure you that I am working everyday to bring a new chapter, but your feedback will help me improve more.

Incase you have any questions or doubts, please feel free to leave your comments below. I will try to answer them as soon as possible. There will be a new chapter on this topic very soon and more topics are already in queue. So, if you like to continue this, I will recommend you to subscribe to this blog and you will be notified as soon as they are available for your read.

Have a nice day ahead … happy learning.

Go to Beginning with TypeScript Tutorial Index page.

TypeScript Tutorial: Interfaces in TypeScript (Chapter 5)

We are now on a ground where, when we look around, we can see the other aspects of the TypeScript language clearly. Basic building blocks of any language are DataTypes and Functions, which we know now with the help of our previous chapters. Here in this chapter we are going to begin our journey for OOPs by looking into the interfaces in TypeScript.

A TypeScript Tutorial for beginners on TypeScript

Interfaces in TypeScript

When we talk about an interface, we think about having a blue print of any object which would like to be defined in the terms presented by that interface. Means, if an interface says that the object must have a property named a, that’s a hard line. No object, can cross that line, if they want to implement that interface.

Other aspect of interface is to set a communication restraints. For example, if a function accepts an interface then it should be called only with the object that complies with that interface, nothing else. Knowing all that, let’s see what interfaces in TypeScript looks like.

A Simple Interface

Here is an interface in its simplest way written in TypeScript.

interface IPerson {
    firstName: string;
    lastName: string;
}

Above code is defining an interface, that prescribes how a person in the system should look like. Whether it is a single property or many, interface can be beneficial in putting a restraint on how the data is moulded and used. Below example shows the basic usage of interfaces in TypeScript, passing it as a parameter to a function.

function getFullName(person: IPerson) {
    return person.firstName + ' ' + person.lastName;
}

let person = { firstName: 'John', lastName: 'Doe', age: 28 }

console.log(getFullName(person));

You are able to pass an object which has both the required properties, so it is possible to call the function with that object.

Properties can be Optional

Unlike other object oriented languages, interfaces in TypeScript can have optional properties. That means, the objects can be created without defining those properties and can still be used without TypeScript complaining about them. Let’s see the above example of a person interface with optional properties.

// interface with optional properties
interface IPerson {
    firstName?: string;
    lastName?: string;
}

// function using the interface
function getFullName(person: IPerson) {
    return person.firstName + ' ' + person.lastName + ' (' + person.age + ')';
}

// person object without the firstName
let person = { lastName: 'Doe', age: 28 }

console.log(getFullName(person));

When you try to compile the above code, it is not going to complain about the missing firstName property, but about the age property. I know this code is eventually going to break, but it is just to demonstrate the pain point of TypeScript compiler.

Interfaces a Blue-Print for Functions

Interfaces in TypeScript can be used to define how a function would look like. Let’s see how, with the below snippet.

// function type interface
interface PersonNameFunc {
    (fristName: string, lastName: string): string;
}

// function variable
let PersonName: PersonNameFunc;

// function defination
PersonName = function (fname: string, lname: string) {
    return fname + ' ' + lname;
}

Interfaces has no role in JavaScript

Stop thinking about JavaScript, when you are learning TypeScript. I know you can’t … me either. I have also seen the compiled output, when I wrote my first interface in TypeScript. I know you are also as surprised as I was, seeing an empty JavaScript file. The truth is, Interfaces doesn’t get compiled into JavaScript in anyway. They just play their part in TypeScript and die over there. I know, I might have shown you this earlier in this posts, but it is never late.

That’s not all!

While there are a of things to learn with Interfaces in TypeScript, I will be stopping here for the scope of this posts. You will be learning a bit more in upcoming chapters. You can continue reading this blog for more posts on similar tutorial and subscribe to get a notification as soon as new posts are available.

I will leave you here with all your studies and learning, while I prepare myself for the next post. In case you have any doubt or queries, please feel free to leave your comments below. I will try to answer all your questions as soon as possible. Your feedback is important for me, so that I can produce more quality posts on exciting topics.

Have a nice day ahead … happy learning

Go to Beginning with TypeScript Tutorial Index page.

TypeScript Tutorial: Functions in TypeScript (Chapter 4)

A TypeScript Tutorial for beginners on TypeScript

Functions in TypeScript

I am aware that you know what a function looks like in JavaScript, but still lets have a look again. Here is how you have defined the functions till now and these are not different than functions in TypeScript.

// a named function
function sum(num1, num2) {
    return num1 + num2;
}

// an anonymous function
var sum = function(num1, num2) {
    return num1 + num2;
}

I am sure you will be thinking what’s the difference, nothing actually till now this is exactly same in both languages. All the functions you define in JavaScript are 100% valid functions in TypeScript. (You remember that TypeScript in an extension of JavaScript).

Constraint the Parameters with Types

If you use the above functions you can use and pass any data type and it will execute and will give you results also. Let’s see the outcomes of the few calls to above function.

console.log(sum(1, 2)); // prints 3

console.log(sum('John ', 'Doe')); // prints John Doe 

console.log(sum('IsScuccess: ', true)); // prints IsScuccess: true

So, I can literally pass any type of data and that function is doing its task flawlessly. But are you sure, that was the intended behaviour of this function. No! It should sum two numbers. So let’s see what functions in TypeScript looks like by introducing the parameter types.

function sum(num1:number, num2:number) {
    return num1 + num2;
}

console.log(sum(1, 2)); // prints 3

console.log(sum('John ', 'Doe')); // compile error

console.log(sum('IsScuccess: ', true)); // compile error

Now we are talking TypeScript (partially though). The compiler will complain, throw error, but that’s all it can do. It will still compile and the generated JavaScript will still behave the way it was earlier. It is just a notification to you that you are doing something wrong. So, with TypeScript you get the intimation in advance that you might be doing it wrong when you are passing a non-numeric data to the function parameters.

Introduction to Return Type

No, I have not seen that coming. You can constraint the functions in TypeScript for the return type too. That means if the function is trying to return a type other than the intended type or you have forgot to return anything, TypeScript will complain … Again Only Complain. Let’s evolve above function here by adding a return type to it.

// a function with return type
function sum(num1:number, num2:number):number {
    let result = num1 + num2 + '';
}

Oops! there is nothing returned from the function and thats a pain point for TypeScript. Let’s try to fix that.

function sum(num1:number, num2:number):number {
    let result = num1 + num2 + '';
    return result;
}

Wait … what? TypeScript is still complaining of your misdeeds. It will … why not? One side you are telling that you need a number as output from the function and within the function you are corrupting that sense by returning a string. number + string = string, I am sure of that. Let’s wake the function in all its glory.

function sum(num1:number, num2:number):number {
    let result = num1 + num2;
    return result;
}

Yup! no mistake this time. That’s the true nature of human kind. We learn from our mistakes. I intentionally pick that route, so that you can learn from my mistakes and I hope you did.

Whats More …

Now, it can be a possibility that you don’t intend to return any thing from that function. So, you can use (Introducing: Void data type) “void” as a return type. In this case, if you “by mistake” return anything from the function, you will give TypeScript another reason to cry. Bellow snippet show the use of void.

function submitUpdates(postId: number, updateTime:Date):void {
    // do some work like call a webhook and forget
}

That’s not all, you have much more to learn with functions in TypeScript, but it is a talk for some other day. You will be able to start your journey with this much knowledge and leave the thriving part for the day in future. I am not saying that the knowledge is not important, but we will come back to this topic, when you have touched all the aspects of this tutorial here. I will take a leave for now and will let you continue your studies. Have a nice day … happy learning!

Go to Beginning with TypeScript Tutorial Index page.

TypeScript Tutorial: Types in TypeScript (Chapter 3)

A TypeScript Tutorial for beginners on TypeScript

Types in TypeScript

Types are the biggest addition to the TypeScript over JavaScript, which makes it much superior. During this post we will be seeing most of the types in typescript. This post will bring you to a levelled ground for the remaining of the building blocks of the TypeScript language.

Primitive Types

Like many other matured programming languages, TypeScript also supports these basic types. Here are the primitive data types in TypeScript.

  • String: when an array of characters are required to be stored, like name, email, password etc, this type is used.
  • Number: like integer, decimal, hex, float, binary etc are stored in this type of variable.
  • Boolean: when a true or false value has to be stored in TypeScript we have to use this type of variable.

We can create these variable as shown in the snippet below.

// string
let color: string = "blue";

// number
let age: number = 6;

// boolean
let isDone: boolean = false;

Note the word “let” as compared to “var”. We will see the difference of this in the upcoming chapters.

Arrays and Tuple

Array type in TypeScript is now typed, means as compared to JavaScript, you can define the data type of the member elements of a given array variable. However there is a fallback option available for storing any type of data in array in TypeScript. We will learn about that later in this post. So, an array can be defined as shown in the snippet below.

// JavaScript Style
let colors: string[]

// Generic Type
let colors: Array<string>

Tuple is very similar to array with only difference of having the first few number of elements with predefined data type. Say for example, you can have a tuple something like below snippet.

// tuple
let person: [string, string, number] // firstname, lastname, age

// allowed assignments string
person[0] = "John";
person[1] = "Doe";

// allowed assignments number
person[2] = 28;

// out of know indices 
person[3] = 1984 // outside of known indices [string | number]
person[4] = "Bangalore" // outside of known indices [string | number]

// invalid assignments;
person[0] = 28; // should be a string
person[3] = true; // only string | number as that's known to this variable

Enum

While the above datatypes might have shown you the strengths of TypeScript, enums can be an additional arm itself. Here is an example of enum datatype.

enum Weekdays {
    Sunday,
    Monday,
    Tuesday,
    Wednesday,
    Thursday,
    Friday,
    Saturday
}
// get the weekday number
console.log(Weekdays.Monday);

// get the weekday name as string
console.log(Weekdays[Weekdays.Monday]);

Any

When we say that TypeScript is an extension of JavaScript, there should be some flexibility also like JavaScript. With “any” type, we get that, where we can store any type of data, while remaining within TypeScript bounds. Here is the example of this.

// initialised with number
let someData: any = 30;

// can store string
someData = "John Doe";

// can store boolean too
someData = false;

Though we have seen many of few types in TypeScript, the possibilities are not over yet. You can always refer to the official documentation of ever evolving TypeScript when and where you have doubts. Comments on this post will always remain open and I will try to keep this post under a watch for your questions and feedbacks.

You can also subscribe to the blog if you are interested to follow and get notified of upcoming chapters of this tutorial. I will be posting the next chapter in this tutorial very soon. Till then … enjoy coding.

Go to Beginning with TypeScript Tutorial Index page.

TypeScript Tutorial: IDE (Chapter 2)

A TypeScript Tutorial for beginners on TypeScript

Integrated Development Environment

We will be setting up an IDE in this post for TypeScript. Yes, you got me right … an Integrated Development Environment. We will be using this IDE during the span of course “Beginning with TypeScript Tutorial“. For me an IDE comprises of below parts mainly:

  • An Editor: where you can write the code and format it so that it can be easily readable by a human eye.
  • Some Intellisense: When you start writing a code, if you can see what you are doing or tend to do, it is a great help for you as compare to just be able to read it. Intellisense provide strengths to your IDE, so that it can help you write a better and accurate code.
  • Compiler: So you are done with your code and now you should be able to convert that into something, which can be executed in its environment. A compiler does that. (As TypeScript is a language, which requires to be compiled into JavaScript, so we need a compiler here.)

Let’s Go Shopping

When we go out for shopping, we try to go to one place where, we can get all what we need in a single stop. But, it is not always true. In some cases you would want to step out and find things at different places, whatever reason you may have. For us the reason is … We want all that comes free. During the course Beginning with TypeScript Tutorial, we will be trying to use whatever comes free. (macs are not cheaper, which I am going to use during this tutorial, but rest assured that all this can be done in a Windows PC too.) Here is our shopping list.

  1. Atom Editor: I am going to use Atom Editor from GitHub. You can argue or whatever you want, but that’s the editor of my choice as compared to Visual Studio Code. I am not doing a product comparison here. But, if you think that you can find the remaining ingredients to match the recipe, you are free to use whatever you like. (Of course you are welcome to discuss the pros and cons below in the comments.). Here are the extensions you will require, if you opt for Atom Editor.
    • atom-typescript: This extension transforms the Atom Editor into a full blown IDE for typescript. Once you have that extension, you may not require any other extension at all for TypeScript at least. (disclaimer: depends on the individual requirements too.). This extension may install another extension named linter, in case you already don’t have that for some other reasons.
    • script: This is simple extension, which help you to execute the code from within the editor. We will need this to test our compiled JavaScripts.
  2. NodeJS: This is a JavaScript runtime engine, where you can run your JavaScript code.

On the Cooking Table

  1. Download and install the Atom Editor of your operating system from the link provided above in the list.
  2. Open Atom and got to preferences. You should see something like this:
  3. Navigate to Install tab from the left panel and search and install atom-typescript and script packages. Once you install, Atom may prompt you to restart. After this process you should see the installed packages something like this:
  4. Your Editor is ready.
  5. Now you are required to install nodejs. Please download and install the application from the link provided in the list above.
  6. You are all done and ready to cook.

Let’s Test the Environment

We are almost ready with all the things. As the last step before we start on the course “Beginning with TypeScript Tutorial” and do some real work, let’s just check our environment.

  1. Create a folder named testing on you computer and drag-drop that folder in the editor. This should show a tree view on the left side of the editor listing the folder there.
  2. Right Click the folder and select New File from the menu. This will prompt you to provide a file name. I have given name as testing.ts. The file should be opened in the editor. Here is how your edit should look like:

    Notice the TypeScript pane at the bottom of the editor and a message in there saying “no tsconfig.json”. That’s your cue to add a tsconfig.json to your folder.
  3. Press Shift + Command + P, which should bring you a command palette. Here you can start typing tscongif.js and select the item Create Tsconfig.json Project File.

    A new file will be created in the folder. Just leave that file as it is.
  4. Now in testing.ts enter the text console.log("Hello World!") and save it. As soon as you save the file, you should see a new file created in the left navigation, named testing.js. This confirms that all the required things are installed properly and working as expected and TypeScript is getting compiled into JavaScript.
  5. Right click the newly created file and select Split Right to open the file and observe the contents. Here is your output.

Moving Ahead …

We have all the prerequisites the course Beginning with TypeScript Tutorial and ready to dive. I will conclude this post here with more to come in the next post. We will be learning about type in the TypeScript in the next chapter.

In case you have any questions, please leave your comments below. I will be really happy to answer them as soon as possible. I hope you liked the contents here and in my previous course on AngularJS with ASP.Net MVC.

Your feedback is important to me as it will improve the contents in my upcoming posts. Have a nice day … Cheers!

Go to Beginning with TypeScript Tutorial Index page.