Getting Started with TypeScript: Angular 2 (1/N)

Hello All,

Thanks a lot to all of you for liking my first AngularJS 1.X series and I am very glad to receive thousands of responses and feedback. I was planning to write the similar series on Angular 2 but got bit busy with various things. Also I was working on a course on ASP.NET Web API using ASP.NET Core which you can find at Learning ASP.NET Web API. In the mean time so many blog readers requested me for the same. Today I am going to write first post on Angular 2, specifically Typescript.

Download the pdf version of my AngularJS 1.X series from here.

As Angular 2 was first announced by Google around two years back in 2014 since then various changes has taken place in the framework and continuing. The final release is yet to be out. Due to the kind of breaking changes with previous version it is introducing, initially there were lots of apprehensions in the community around it. But the Angular team has successfully addressed most of the concerns as the times passed. Now it is approaching to final release and we already have couple of RC releases so we are not too late with it. But it is high time to start.

Why Angular 2?

It is one of the most asked questions about Angular 2. As we have already a robust framework (AngularJS 1.X) which is serving the purpose quite beautifully for small to large enterprises, do we need this kind of changes at all?

The answer is Yes. There are quite a few reasons. Let’s see that

  1. There are major performance improvements in all the areas whether it is bootstrapping, Data binding, event handling etc. Leveraging Web workers and using other libraries also got simplified.
  2. As this is the age of mobile, Angular 2 has been developed by keeping it mind since beginning. The same code renders differently based on browser or mobile app.
  3. One of the hardest things to understand in Angular 1 was $scope which is no more in Angular 2. Angular 2 uses zone.js for the change detection.
  4. No more controllers and we will deal with Components here
  5. Write less code with Typescript and leverage the OOPs concept.

So we have seen some of the key benefits of Angular 2 but it does not mean you just upgrade the Angular 1 to 2. As it is completely new framework with little commonalities with previous one, it is advised to use it with new applications while old one can happily use Angular 1 without any issue.

How to start with Angular 2?

In AngularJS 1.X, we have used plain JavaScript for writing the code but as we are seeing for long, writing JavaScript code for enterprise level applications is quite tough and become unmanageable as the time passes. Even for small applications as they grow, it becomes tough to manage. Angular 1.X resolves this problem a bit by structuring the code and writing loosely coupled system. But JavaScript itself is not a type-safe language and does not allow features of OOPs. To overcome these problems, Angular Team announced AtScript at ngEurope conference in Sep 2014 and shared the new (Angular 2) framework is developed using it. Microsoft was also working on similar language TypeScript so both got together and in March 2015, they announced that the features of AtScript will be available in TypeScript 1.5 and the complete Angular 2 framework got built using TypeScript.

ECMA which defines the standards for JavaScript also understood the challenges of it and came ECMA 6 (June 2015) which includes the concept of classes, modules etc. and ECMA 7 in June 2016. Lets see how does all fit together.

Typescript

We can see that TypeScript is super set of all, it means we can leverage the features of all the standards and languages. But currently most of the browsers supports the ECMA 5 only, it means our code cannot run as is. For that we have few compilers like tsc, webpack which compiles the typescript code to normal JavaScript so that it can run smoothly in all browsers.

As Typescript and AngularJS looks made for each other so we will use TypeScript for writing Angular 2 code and in our initial posts we will discuss some core concepts of Typescript and then introduce Angular 2. After learning basics of TypeScript, learning Angular would be very easy.

We will start learning the Class. Yes you have read it correctly. Class is new construct that got introduced with ECMA 6 and further more features are added via TypeScript.

Choosing Editor

So what editor should we use for the same. There are various options and some of them mostly used are

  1. Visual Studio 2013/2015,
  2. Visual Studio Code/Community (free)
  3. Sublime
  4. WebStorm and many more

You can use any of it. You can go for Sublime if never used Visual Studio or you can try Visual Studio community version which is free. For more details and how to use these editors, refer here.

I will be using Visual Studio and for that you just need to install a plugin and it provides very rich editor with all intellisense support and compile time errors.

Creating Class

Classes in typescript is almost similar to C# but here it is more flexible and requires less code. So let’s our first class

class Person {
    // Three properties which is by default public.
    // Types are written after the variable using the separator :
    firstName: string;
    middleName: string;
    lastName: string;

    // Class constructor accepting three parameters. 
    constructor(firstName: string, middleName: string, lastName: string) {
        this.firstName = firstName;
        this.middleName = middleName;
        this.lastName = lastName;
    }

    // Member function of the class
    getFullName() {
        let fullName = this.firstName + ' ' + this.middleName + ' ' + this.lastName;
        return fullName;
    }
}

We have written a class Person which has three properties firstName, middleName and lastName. In this type of variables are provided after the writing itsname with a sperator “:”. All the members are by default public so these can be accessed and updated using class instance. Then we wrote constructor using the keyword constructor which accepts three parameters and initialize the internal properties. Here you can see the similar this keyword as C# which refers to current instance of the class. Also I added another method getFullName which just concatenates all the three properties and returns full name. Here you can see that we don’t need to write any keyword like function etc so we can see that it requires a lot less code and more contextual keywords.

let person = new Person("Brij", "Bhushan", "Mishra");
console.log("Mr " + person.lastName);
console.log(person.getFullName());

Now creating instance of the class is similar to C# using new keyword with passing all the parameters in constructor. As we have just one constructor we would not able to create instance by parameter less constructor. We also see another keyword let which I am using instead of var, we will discuss the differences in some later post but let should be preferred. Calling method is simple and here we just printed values in console.

Using Inheritance

Inheritance is well supported in TypeScript so we can easily extends any class. Here we need to extens keyword instead ‘:’ used in C#. Let’s extends our person class and create Employee class

class Employee extends Person {
    // Two more properties added
    employeeId: string;
    salary: number;

    // Constructor takes five parameters now. Three from base class and two derived class
    constructor(firstName: string, middleName: string, lastName: string, 
                employeeId: string, salary: number)
    {
        super(firstName, middleName, lastName) 
        this.employeeId = employeeId;
        this.salary = salary;
    }

    getSalary() {
        return this.salary;
    }
}

As mentioned earlier, extends keyword got used for for deriving a new class. In the constructor, we used another keyword Super to call the base class constructor and that should be called inside the constructor, not after the colon (:) as C#. There we also required to use base keyword for the same.

Implementing Interface

We can also create interface and that may be implemented in a class. Let’s create an interface IBonusCalculator as

interface IBonusCalculater {
    getBonus()  
}

It is similar to C# and have just one method getBonus. To implement it, we need to use implements keyword. Let’s implement it in our Employee class

class Employee extends Person implements IBonusCalculater {
    // Two more properties added
    employeeId: string;
    salary: number;

    // Constructor takes five parameters now. Three from base class and two derived class
    constructor(firstName: string, middleName: string, lastName: string, employeeId: string, salary: number)
    {
        super(firstName, middleName, lastName) 
        this.employeeId = employeeId;
        this.salary = salary;
    }

    getSalary() {
        return this.salary;
    }

    // Implementing IBonusCalculater's method
    getBonus() {
        return this.salary * 0.3;
    }
}

So we have seen that Class in typescript provides all the key features of OOPs and uses more relevant keywords like extends, implements, constructor etc than C# which makes it more developer friendly and readable.

Now I am going the last topic which will make you excited.  Say we have two classes and there instances

class Book {
    name: string;  
}
class Video {
    name: string;
}

Are both different type. Let’s see this

let b = new Book();
b.name = "HTML and CSS";

let v = new Video();
v.name = "Learning ASP.NET Web API";

function PrintName(b : Book) {
    console.log(b.name);
 
}

PrintName(b);
PrintName(v);

Will it compile?

Yes and run without any error. Surprised.

It will print the book and video name accordingly. Typescript checks the property names for Type comparison. I find it more useful as although they are different classes but behind the scene both are same. If we add some another property in Book only then it will throw an error because the type of parameter is Book and when video does not have the property while vice versa works but we will not be access the new property of video.

Conclusion

In this post, We have started with little bit history of Angular 2 and discussed that how TypeScript became the primary language for Angular 2. We saw that TypeScript is superset of JavaScript including ECMA 6, ECMA 7 standards and ultimately it is converted in normal JavaScript file which is compatible with every browser. We discussed the first key concept Class with example and later we saw the most important thing that two different class with same properties are considered similar here. In the next post, we will discuss about Decorator and Components.

Cheers,
Brij