ToDo Application: Setup TypeScript Project

There are many ToDo or task management applications out there, written in many programming languages and for almost all the platforms. A ToDo application at its core is the simplest application one can think of. This makes it the right candidate for practicing or brushing up any language’s skills. Which is the same reason, we have picked up this as the center of this tutorial on building an application with TypeScript. This post is second in this series, where we will setup TypeScript project. In case you have not started from the beginning or very beginning (learn typescript), you can do so before continuing here.

Setup TypeScript Project

Before we start setting up our project and begin the development let’s see what we are going to build. Here is the screenshot of the minimal implementation of the application.

Sneak Peek
Application Sneak Peek

Here you are going to build a simple web application which has the capabilities of

  • adding new tasks in the list
  • storing in browsers local storage
  • show the task list with delete and complete actions
  • select tasks to edit them.

So let’s not indulge ourselves on that anymore but setup TypeScript project. I will explain the steps here one by one for each of the component of this project.

jQuery Typings

We will be using jQuery in this application for DOM manipulation and few other simple tasks. The jQuery script will be linked to the HTML after loading dynamically using require.js. Also, for TypeScript compiler and intellisense to recognise the jQuery functions, we are required to have the type definition file for jQuery in our folder and referenced in the TypeScript code files. We will be using definitelytyped repository to get these.

First of all let’s install the typings manager

npm install typings -g

Once you have installed the typings manager globally, its time to install the jQuery typings. For this you have to navigate to the project folder (in case you have not created a folder for your project, its right time to do so now). Open the folder in your favorite terminal and enter the below command.

typings install dt~jquery --save --global

This will create a few files and folders in your project folder as shown below.

Project Folder after installing jQuery Typings

Let’s not go into much details here but just understand that if we reference the index.d.ts from the typings folder into our TypeScript code we will be happy to go.

Bower Components

Next step is to get bower and using that, install jQuery, Bootstrap and Require.JS. Bower is a web package manager which can be used to manage third party library dependencies for your application. You can install bower using the command below (this is installed globally as we did for typings).

npm install bower -g

Once bower is installed, you have to enter the below command in the terminal, while being in your project root.

bower install jquery requirejs bootstrap

After the above command is finished successfully, you should see the below structure of your project folder

image folder structure
Folder structure after installing the bower components

Compiling TypeScript

I am assuming that you have already done the IDE setup as explained here in this post, So its time now to create a tsconfig.json file as per the snippet below.

{
    "compileOnSave": true,
    "compilerOptions": {
        "module": "amd",
        "removeComments": true,
        "outDir": "js",
        "alwaysStrict": true,
        "emitBOM": false,
        "target": "es5"
    }
}

This file tells the compiler that it should compile the TypeScript files as soon as they are saved and output the result into the js folder. Along with that the compiled output will be ES5 compatible and usable by amd module. Let’s create a folder named js and other named ts in our project folder. Create a file main.ts in the ts folder with some simple code in there, just to check if everything is working fine. Here is the outcome of my test.

Compiling TypeScript
Compiling TypeScript

Compiling LESS

I am assuming that you have setup your development environment as suggested in my previous post. We will be however using one more thing in this project and that is LESS as the pre-compiled CSS. LESS can be compiled into CSS so that it can be used by the browsers. We will adding one more package to our Atom editor so that as and when we edit and save the less file, it is compiled into the equivalent CSS.

Please go to your Atom Editor’s settings and navigate to Install tab. Now search for atom-compile-less package and install it. This package will compile your less files into the css files as soon as they are saved.

Create a folder named styles in the root of your project folder and create a new file named main.less in there with the below content (this is just to validate if the less is getting compiled).

a {
    text-decoration: none;
    &:hover {
        text-decoration: underline;
    }
}

Here is something what you should see as the output.

LESS file sample
LESS Compiled into CSS

You will require to enable the auto compile option of this package in its settings page.

In case you are interested in minifying the generated css, there is an option to do so too with this atom package.

At this point, our main project setup is complete and we are ready to write our code for the application. Please let me know in case you have any troubles following this tutorial. I will really appreciate your feedback. It will encourage me to write more such posts and courses. I will take a leave from you now so that I can continue on the next post in this series.

Have a nice day!

Build ToDo Application with TypeScript: Prerequisites

TypeScript is a modern language for the web applications development today which improves the application development efforts and reduces a lot of headache. I have recently completed the Beginners TypeScript Tutorial, where I promised that I will be showcasing the practical usage of TypeScript. So, here with this post we will start our tutorial on how to build a todo application with typescript. Let me name it in advance … Better ToDo

Building an Application with TypeScript

If you have completed a basic tutorial on TypeScript and are wondering on how to put it all together to build an actual application using TypeScript, you are at the right place. During this tutorial you will be able to clear your mind from all that clutter you might have gathered during your learning and build a clear picture of the language.

In case you are coming from the domain of JavaScript, you might be habitual of changing the code and reloading the page. The code you have created is plain JavaScript and it doesn’t require any post processing once you are done with that. Just load it and its done. But in case of TypeScript, you are required to compile your code to get it converted into JavaScript and make it usable by the browsers.

Prerequisites

For this tutorial before we start building our application with TypeScript, we need a few things on our table.

  1. Clarity on the basics of the TypeScript Language
    Incase you are not following this blog and have not gone through the beginners typescript tutorial,  you can go through that here.
  2. Development Environment Setup
    You can the setup instruction here from the beginners typescript tutorial.
  3. Third party libraries like jQuery and Bootstrap.
    we will be getting these libraries as the initial set of our project

We will be using LESS as the precompiled language for the cascading style sheets here. This makes our code much more easy and manageable.

Take Out

At the end of this post you will be able to grasp a clear picture on the core concept of

teaser of the todo application
Application View in a Mobile Device

The other concept, which you will learn during this series is dynamically loading the script files. Although it might not be much helpful in this single page application, but you will be able to utilize the knowledge somewhere else.

One more, thing I would like to point over here is that our main focus will be on the TypeScript. We will not be going in depth of the application UI design or learning jQuery or Bootstrap.

Creating Anchor

I will be continuing on this topic on my next  post. In the next post we will be setting up our project, download all dependencies and compile TypeScript. I will be posting the links to the next post below here. You can subscribe to the blog to get notification of the posts as and when they are available.

Please leave your questions below in case you have any. I will really appreciate your feedback, as they will help me build better content while motivating me to write more.

Meanwhile, you can go through other course on AngularJS with ASP.Net MVC, in case you are interested. Hope to see you again with my next post. Till then … have a nice day.

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.