TypeScript Tutorial: Using Typings (Chapter 9)

TypeScript can understand JavaScript (respectfully) functions as they are with that old reference syntax. But, it really loves the taste of its own flavours. There are many ways you can use a JavaScript library with TypeScript and make it all work, whereas using Typings it makes yours and TypeScripts life really easy. In this chapter we are going to see what are Typings and how they makes the life of developer easy.

A TypeScript Tutorial for beginners on TypeScript

What are Typings?

Just consider Typings as the interface for TypeScript to understand the vast world of JavaScript. A Typings file includes the definition of all the functions in a JavaScript library. In other words it is defnition of a JavaScript Library consumed by the TypeScript compiler and Intellisense so that they know what a function does and what all properties of an object are.

Why Typings?

Take an example of a library, used and known today to almost every web developer … jQuery. That library is pure JavaScript (In our upcoming chapters in practical use of TypeScript, we will be using jQuery too) and exposes a single variable in the global scope ‘$’. This single variable has the definition of all the functions this library supports.

What if in our application written in TypeScript need to use that library? Well, there is no one stopping you to do that. The only caveat here is that your compiler will not know it and will warn you about that. And your IDE will not help you find the available methods in that library. You will be able to still compile and use the output JS in your program as you know that you have included jQuery as a script tag. Let’s build a smaller example. Say you have a JavaScript library which defines a function like below.

File: jsLib.js

function SayHello (name) {
    console.log("Hello! " + name);
}

and we want to use that function in our TypeScript code like this.

File: testTypings.ts

module tester {
    export var useJSFunction = function() {
        SayHello('Mark');
    }
}
tester.useJSFunction();

If you compile the above code you will see that compiler will complain “not able to find the name ‘SayHello'”. If you include these both files in your web page and run, you will be able to see the output without any issue and your application will run just fine.

Now, you may say when the output is there and your application is running the way it should, what else you need?

Using Typings

Probably you are missing the point here … the core USP of TypeScript … definition of types. Means you and compiler knows what the code should look and behave like. So its time to introduce our library’s definition over here.

File: jsLib.d.ts

declare function SayHello(name:string): any;

and reference this file in the testTypings.ts file.

///<reference path="./jsLib.d.ts" />

module tester {
    export var useJSFunction = function() {
        SayHello('Mark');
    }
}
tester.useJSFunction();

By using Typings makes both you and compiler happy, as you know what you are coding and compiler knows what it is compiling. Below screenshot proves this with the intellisense.

All the definition files are saved with a file extension ‘.d.ts’ and by only being there in the TypeScript project environment, they are automatically available for the compiler and intellisense (We still include the reference for the clarity of the developers).

Getting Type Definitions of the External Libraries

Coming back to the jQuery, this is a huge code and there are hundreds of functions over there. Do you need to convert all those jQuery functions into the type definitions?

The Answer is No! … If you are lucky enough or using a popular library in your project, you can get the definition files from internet. There are npm and bower packages and repositories like DefinitelyTyped or typings, which can help you get your hands on the typings of your favorite library. Once you get the typings, its as simple as including that file in your project along with the js library.

Using Typings makes it possible to work with these libraries as if they are available right there in your project, even if you are including them from CDN later at the client side.

There is More

The intention over here is to keep these tutorials simple as much as possible and help you do an easy transition from JavaScript to TypeScript. If you have searched the web, you might have seen the “include” or “require” syntax. Trust me that’s a different level of talk. We will be talking all about those techniques in our upcoming series on Advanced TypeScript.

With this I am concluding this series here on Beginning with TypeScript. I remember that I have told you all about the practical use of TypeScript at the End of this tutorial. I am not ditching that. In the next post we will start building a simple ToDo Application using TypeScript. Here is the sneak peak of the same.

In case you are interested in that, I would recommend you to subscribe to this blog, so that you are notified as soon as this or any new topic is published here. Hope you enjoyed this little tutorial. Please leave your feedback or any queries you have, below in the comments. I will be really happy to help you out with your queries.

Have a nice day and happy learning!

Go to Beginning with TypeScript Tutorial Index page.

TypeScript Tutorial: Modules in TypeScript (Chapter 8)

Consider you have a business logic, which requires to be clubbed together and executed in an isolated scope. TypeScript modules comes to rescue you from such situations. We are going to understand basics of modules in TypeScript during this post.

A TypeScript Tutorial for beginners on TypeScript

Modules in TypeScript

Assume you have an application for managing Tasks. You would like to segregate the definition of Task entity and all the operations related to that for rest of the application. We can define a module for that and separate them from rest of the application.

Modules are executed within their own scope, not in the global scope.

This means that variables, functions, classes, etc. declared in a module are not visible outside the module. If you want to expose and use certain features of a module outside of the module, you will require to export them. Let’s see a simple example.

module ToDoApp {
    class ToDo {
        Text : string;
        IsCompleted : boolean;
    }

    let list: Array<ToDo> = [];
}

In the above code we have defined a module which limits the scope for ToDo class and a list of ToDos.

Exporting Features

Now if we try to create an instance of ToDo class or access the list variable outside the module block, we will not be able to do so. We need to export these features from the module before we can use them outside the block. Here is how the module definition looks like after enhancing the same module with localized and exported features

module ToDoApp {
    var saveLocalData = function () {
        localStorage.setItem('todos', JSON.stringify(list));
    }

    export class ToDo {
        Text: string;
        IsCompleted: string;
    }

    let list: Array<ToDo> = [];

    export var addToDo = function (todo: ToDo) {
        list.push(todo);
        saveLocalData();
    }

    export var removeToDo = function (todo: ToDo) {
        list.splice(list.indexOf(todo), 1);
        saveLocalData();
    }

    export var getList = function() {
        return list;
    }
}

With this code, the save operation and the list itself is now hidden from the global scope and the the ToDo class and operations which can be performed in the ToDo app are exported.

Exporting / Importing Modules

We have seen the concept of exporting the features of a module outside the module. This is useful in case the consumer of that module remains in the same file, where the modules is defined. But, what if the consumer is in the separate file.

In this case the defined module can be exported and with the help of the module loaders (requirejs, commonjs) they can be imported into the file where they are required. Modules import works at the file level, which means all the code blocks in the file will have access to the imported module. Let’s see the example of the same by creating 2 files

// todoModule.ts
module ToDoApp {
    exports ...
    ...
}

export = ToDoApp;
// app.ts
import ToDoApp = require("./todoModule");

let todo = new ToDoApp.ToDo();

todo.Text = "Buy Milk";
todo.IsCompleted = false;

ToDoApp.addToDo(todo);

We have exported the ToDoApp from todoModule.ts and then imported the same from app.ts. Once the module is imported, we are able to consume the exports from that module.

There are more ways to import and export the modules in typescript but, this is the most widely used syntax. We will learn more about modules in our upcoming tutorial on Learning Advanced TypeScript. I will recommend you to keep a watch on this blog by subscribing.

In case you have any doubts and would like to provide any feedback, please feel free to leave a comment below. I will really appreciate your feedback and will be really happy to prove the answers to your questions. In the next chapter we will be learning about the concept of Typings and the purpose of having them.

Have a nice day and happy learning!

Go to Beginning with TypeScript Tutorial Index page.

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.

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.