TypeScript Tutorial: Understanding Inheritance (Chapter 7)

Till now we have talked about DataTypes, Functions, Interfaces and Classes during our short tutorial series on beginning with TypeScript. I hope you have enjoyed reading them as much as I did writing. I have recently updated the topic list to include modules and typings in there. In case you have not seen the start of this tutorial, you can go to the beginning by following the link shared at the bottom of this post. By the way Understanding Inheritance is the topic of this post.

A TypeScript Tutorial for beginners on TypeScript

Understanding Inheritance

I am not going to bother you with huge technical jargons here, but a simple statement, “when some class of object owns a property or behaviour because of its parent, it is called inheritance”. Wasn’t that easy peasy? You have eyes of your mother, when said that means you have inherited that property from your parents. In the world of Object Oriented Programming the similar rule of thumb is portrayed. You can define a class and then tell that this is going to have few properties from another class. TypeScript also have provided this capability to the developers to use this principle.

Employee is a Person

In the OOPs world a similar statement is very commonly used. Let’s understand that with an example here.

// person class
class Person {
    // parameterized constructor
    constructor(public FirstName: string, public LastName: string) { }
}

// employee extends a person
class Employee extends Person {
    public JobTitle: string;
}

let employee = new Employee("John", "Doe");

employee.JobTitle = "Manager";

Above code solves two purposes, one to justify our statement and second to demonstrate the inheritance in TypeScript. With this code we can clearly say that an Employee is a person but a person is not an employee. That means if we have an Employee, we can deduce that he is a Person. But, if we have a person, we can’t tell that he is an Employee. That means i can create and instance of Employee and store that in a Person not vice-versa. The below code block will give you error during the compile time, ‘Type ‘Person’ is not assignable to type ‘Employee’.

// person class
class Person {
    // parameterized constructor
    constructor(public FirstName: string, public LastName: string) { }
}

// employee extends a person
class Employee extends Person {
    public JobTitle: string;
}

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

let employee:Employee = person;

Multiple Inheritance

Understanding inheritance is not that simple, especially if you try to relate everything to real world examples. You may have the features of both of your parents, but in the world of OOPs, it is not possible. As that of many other object oriented programming languages TypeScript also doesn’t support multiple inheritance. That means your new class can only inherit properties from a single parent class. There can’t be a class definition which extends 2 or more classes.

But we can implement an interface, which specifies the required properties, a class definition should have. We have modified the above code to show this.

interface IPerson {
    FirstName: string;
    LastName: string;
}

interface IEmployee {
    JobTitle: string;
}
// person class
class Person implements IPerson {
    // parameterized constructor
    constructor(public FirstName: string, public LastName: string) { }
}

// manager implements person and employee
class Manager extends Person implements IEmployee {
    constructor(public FirstName: string, public LastName: string) {
        super(FirstName, LastName);
        this.JobTitle = "Manager";
    }
    readonly JobTitle: string;
}

So, now we have 2 interfaces for IPerson and IEmployee with 2 classes one implementing only IPerson interface and another extending Person class and implementing the IEmployee. At the end we have a class named Manager, which has properties of a person and an employee. Inheriting from an interface helps us simulating the multiple inheritance and makes our code more extensible.

we have made JobTitle readonly as for a class name Manager the JobTitle must be Manager only in all the instance and that should not be changeable.

Identify a different scenario yourself and try to use inheritance there. As a test practice, create an Animal class and create Mammals and Birds interface to create classes for Cow and Sparrow.

Don’t hold it there!

The above text of this chapter only shows a basic concept of inheritance in TypeScript. There are so many other aspects for understanding inheritance with the perspective of TypeScript, which I will not be covering up here as the scope of this post. But, you don’t hold it there. If you need to go deeper during the beginning of the TypeScript learning process, I will not be stopping you.

My suggestion will be to keep yourself constraint and finish this small tutorial first and then jump into the advanced and more deeper study of TypeScript. I will be posting a few more chapters on this tutorial, which will make your base of TypeScript stronger. Form there you will be able to easy explore more and enhance your knowledge. I will leave you to your decision.

Have a nice day and happy learning!

Go to Beginning with TypeScript Tutorial Index page.

Best Code Editor 2017 for TypeScript

Recently, I have started working on a TypeScript Quick Start Tutorial, where I have mentioned and used Atom Editor as my favorite editor. But, that created a curiosity and forced me to go for a public poll from the developers all around the world. You will not believe what’s the output of that. We are going to see the best code editor 2017 for typescript development here during this post.

A discussion on the public poll results

Context

I have been busy in creating a short tutorial for people who are moving towards TypeScript language. Whatever reason they might have to go for this new language, the idea was to get them quick start on this language. I have used Atom as my favorite code editor during the course and asked the readers to let me know if they have any thing else as their favorite. But, I was not patient enough to wait for their feedback on it, so went ahead and created a public poll.

The Best Code Editor 2017

With the majority (around 1/3rd) of votes Visual Studio Code is the winner. There were three other contestants in the poll,  powerful Sublime Text (around 1/4th votes), furious Atom Editor (around 1/5th votes) and adorable Adobe Brackets (around 1/20th votes).

Remember: It is not about VSCode vs Sublime vs Atom vs Brackets vs Everything else. It is just about how many developers likes which one.

There was a wild card entries for EMACS and VIM as a popular choice which kind of stole 1/10th portion of the votes from the poll. For me, since a long time Atom Editor is a favorite text editor. No! I am still not moving completely to VSCode. Many of my projects has to wait to get the taste of the new editor. There are a few small code projects however, which can immediately be opened in VS Code.

THE Visual Studio Code

The main focus was to pick an editor which is best suitable for TypeScript development and Visual Studio Code has that as its native resident. It has nice intellisense built in task management, support for (not so many and ever growing) extensions, built in support for git, a debugger. There might be many other features, which I am not aware as of now (remember? … it was not my editor till now!!)

Sublime Text

As the runner up contestant Sublime stood with the second most popular choice for the developers. Subline as I remember was the first thing I used as a text editor when I got frustrated with the windows Notepad. However, I quickly jumped away from that as it was paid editor for the commercial environment and I didn’t want do build a taste for it. I use Notepad2 as a notepad replacement for the simple text editor. Though Notepad2 supports a minimal syntax highlighting, it can’t take a place for a code editor (My expectations are little higher for the Code Editor).

Sublime works on the dictionary based intellisense, nice text editing features, light weight, min-maps, multiple cursor support etc. Since, I have not used it as a code editor, I will not be able to give a list of more features on it.

Atom Editor

Even Atom is my daily driver, I will not bug you all with hosts of features of this code editor. I will only say that consider this editor as the base for anything and everything you wish it to be. There are add-on for almost every functionality you may think of. You can really make this editor yours with support of themes (I am using material theme and a host of add-ons). I will suggest you to go and explore the features yourself and give it a try.

Between the Crowd

I don’t want to hurt anyones feeling here as there are many contenders and are really good too. But, how many have favorited them, that is still a secret. During the poll, there were a few names popped up like VIM and EMACS and a noise for their variants and capabilities. You can go to the poll and watch the progress and comments yourself.

At the end its you who has to make a decision on what hits your liking and how much that editor is useful to you. For me, as said earlier, I am going to make a slow transition to the VS Code. I will leave you here with a best of luck for finding your dream editor and a poll result.

Have a nice day and Happy Coding!

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)

I am aware that you know what a function looks like in JavaScript, but still let’s have a look again with a perspective of TypeScript language. Functions in TypeScript are very similar to the one you have defined till now in JavaScript, at least when you begin with them. This chapter will give you the idea and you will realise that they are actually much evolved and advanced.

A TypeScript Tutorial for beginners on TypeScript

Functions in TypeScript

Let’s start by looking on a simple plain JavaScript way of declaring a function. 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.