Check out our Angular Book Series.

Creating Variables in TypeScript - Part 2

I'm working on a longer series of articles about Typescript. This will be extra material to support my upcoming Angular 4 book. This is the second part of that series. Check out part 1.

An important part of programming is the ability to create variables. Let's turn our "Hello World" Variable into a variable. First, we'll do it the Javascript way and then we'll modify it with some TypeScript.

Create a Variable

This is the original demo from the previous section:

function echo(message) {
return message;
document.body.innerHTML = echo("Hello World");

We can easily add a variable in here. First, create the variable:

var message ="Hello World"

The var keyword is the normal way to create a variable in JavaScript. Now, modify the echo() call to pass the variable instead of the string:

document.body.innerHTML = echo(message);

Recompile the code and it will work just as the previous sample:

Define the Variable with Let instead of Var

TypeScript includes a secondary way to create a variable, using the let keyword instead of the var keyword:

let message ="Hello World";

This simple replaces the var command with the let command. Recompile and you'll see the same results. Let is part of the ECMAScript 6 standard, but for maximum compatibility, you probably want to stick to ECMAScript 5 or lower compatibility.

The reason to use the let command instead of var is because the two scope differently. When you use var the new variable is created as part of the function block. If the variable is not part of the function block it is added to the global scope of the page. This is why it is considered a best practice for a lot of code to be included in an IIFE. This can cause unexpected results in some cases, such as when you access loop counters inside nested for loops, or have one function embedded in another. The let keyword always scopes at the block level, so each for loop would be considered its' own block.

Consider this code:

function scopedemovar(){
for(var i = 0; i <10; i++){
console.log('outer i: ' + i);
for(var i = 0; i <10; i++){
console.log('inner i: ' + i);

Although this might be considered nonstandard code because the counter variable for both loops is defined twice and identical it is still perfectly valid. What would you expect the output to be? Try it and run it:

You may expect the outer loop to loop 10 times, but it only loops once. That is because the inner loop changes the value of the counter variable and the stop condition triggers the second time the outer loop tries to run.

Change the var to let:

function scopedemolet(){
for(let i = 0; i <10; i++){
console.log('outer i: ' + i);
for(let i = 0; i <10; i++){
console.log('inner i: ' + i);

Now, each i variable is scoped to its own for block and they do not interfere with each other:

I cut off the full output since it was very long, but you can run the code to see that both the inner and outer loop both execute a full 10 times using the let value.

Add Typing to Variables

An important decision for using TypeScript is to make variables statically typed instead of dynamically typed. We can add a type to the variable definition, like this:

let message : string ="Hello World";

We can change the function definition too:

function echo(message:string ):string {
return message;

The function now includes a typed argument and an explicit return type. When we send in the message variable the compiler checks to make sure that we are sending in a string. Recompile the code and run it. You'll see no differences in the output:

Open up the JavaScript file created by the TypeScript compiler for a bit of a surprise:

function echo(message) {
return message;
var message = "Hello World";
document.body.innerHTML = echo(message);

All your type statements were stripped out. That is because these types are part of TypeScript, but not JavaScript. They allow for compile time checking of values, but do not change the underlying language or how things run in the browser. This is an important distinction to remember as you learn TypeScript. The language is all about improved tooling and compile time validation; not about a new language in the browser.

Keep up to date by reading DotComIt's Monthly Technical Newsletter

Introduction to TypeScript - Part 1

I'm working on a longer series of articles about Typescript. This will be extra material to support my upcoming Angular 2 book. This is the first part of that series.

What is TypeScript?

TypeScript is a strongly typed language which can be used to build web applications. It come with a special compiler that converts the strongly typed language into JavaScript so it can run in a web browser. Since TypeScript is strongly typed, it can offer better tooling than can be used with simple JavaScript. Angular 2 was built using TypeScript and I use it heavily in my Angular 4 book. This article is intended to give you an introduction to TypeScript.

Setup the Project

The first step to creating a TypeScript application is to install the compiler. I'm going to use the Node compiler. First, you'll need to set up the node project. Run this command:

npm init

And follow the instructions. You'll see something like this:

This will create a package.json file that will look something like this:

"name": "01helloworld",
"version": "1.0.0",
"description": "Sample TypeScript Project",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
"author": "Jeffry Houser",
"license": "ISC"

Now install the TypeScript compiler:

npm install -g typescript

You'll see this:

With TypeScript installed, you're ready to write your first Typescript application.

Create Your First TypeScript File

Create a file named hello.ts:

function echo(message) {
return message;
document.body.innerHTML = echo("Hello World");

The purpose of this code is to echo a Hello Word message. The function accepts a string, and returns it. The innerHTML of the document's body tag is set to the results of the function call.

This file would be valid JavaScript, but it works fine since TypeScript is a Superset of JavaScript. We can use JavaScript inside of TypeScript easily. We'll improve on this throughout the article as we introduce more TypeScript specific concepts.

You can compile this file by running this command line:

tsc hello

You'll see something like this:

You aren't given a lot of feedback, but if you check the directory, you'll see a hello.js file:

function echo(message) {
return message;
document.body.innerHTML = echo("Hello World");

There isn't a lot of difference between the original file and the compiled file, that is because our main TypeScript file is primarily JavaScript. This is a place to start and over the series we'll expand our TypeScript knowledge.

Test the Application in a Browser

Now it is time to test the application in a browser. Create a page named Index.html:

<head><title>TypeScript Greeter</title></head>
<script src="hello.js"></script>

This index file loads the hello.js file, which will cause the document.body.innerHTML assignment to be called, which will run function and return the results:

Congratulations! You've created your first TypeScript application.

Keep up to date by reading DotComIt's Monthly Technical Newsletter

Compile Code on the Fly - TypeScript and Gulp - Part 2

This is the second in a series of articles no compiling TypeScript applications with Gulp. Check out Part 1 which covers most of the setup; or sign up below to get our fully detailed white paper.

Gulp allows us to automatically run a gulp task when a certain directory changes. This is built in and we don't need an additional plugin to make it happen. We're going to make a task which will watch for TypeScript files for changes, and then trigger the buildTS task again.

First, let's create a variable to point at the TypeScript source:

var typeScriptSource = [sourceRoot + "/**/*.ts"];

The sourceRoot variable was created in the previous article, and points to the src directory. The wild cards tell Gulp to look at all subdirectories inside the sourceRoot folder.

Now create a gulp task called buildWatch:

gulp.task('buildWatch', ['buildTS'], function(){

You'll notice that there are three arguments to this gulp task, something we hadn't seen before. The first is the task name, buildWatch. The second is an array of strings with each string represents a gulp task. These tasks will run before the third argument's function is executed. Here we are only running one task, buildTS, before starting the buildWatch task.

Here is the function code:,['buildTS']).on('change', function(event){
console.log('Event Type' + event.type);
console.log('File Path' + event.path);

We use the watch() function on the Gulp object. It accepts two arguments. The first argument is a source array, in this case the typeScriptSource value. The second argument is a task array. In this case just the buildTS task. Reading this in English, it says watch for files that match typeScriptSource, and when something changes run the buildTS task. Dot notation is used to daisy chain an 'on' method to the watch. When the change event occurs, the type of event and modified files are output to the console.

Run this script:

gulp buildWatch

You'll see something like this:

The important thing to notice is that the console does not go back to a command prompt; the code is left running in the background. Change some code to see what happens:

As you save files, the script automatically notices, and reruns the appropriate task. You'll get console information about the file that has changed.

Overall, I find the watch task to be a very powerful development tool.

Yes, I want to get your white paper on building TypeScript applications

Building HTML5 Applications with TypeScript and Gulp - Part 1

TypeScript is a newish language for application development on the web. It is a superset of JavaScript, and supports things like static typing and class based object oriented programming. Static typing, particularly, can offer improved tooling over what is currently available for simple JavaScript programming.

TypeScript can be used for any web application, or even on the server side with NodeJS. It is the recommended language for Angular 2 applications. TypeScript is compiled to regular JavaScript for deployment and testing. This white paper will explain the infrastructure we use to make this happen.

The TypeScript Application

Before we start to look at the build process, let's look at a super simple TypeScript application. We'll need some code to compile. This code borrows heavily from the official TypeScript tutorials. It will add a 'hello world' message to the body of an HTML page.

Create a directory for this setup. The final directory setup will look something like this:

This is a description of each directory:

  • TypeScriptAndGulp_Article: The root directory will contain the script files for running Gulp and config file for NodeJS.
    • build: This directory will contain the final, processed, build.
    • node_modules: This directory will contain the NodeJS package, such as Gulp and TypeScript, to needed to perform the actions.
    • src: This directory will contain the application's source files.

We will create most of these files and directories as we move through the process.

For now, I named the project directory TypeScriptAndGulp_Article. Start by creating the src directory. I always separate the source code, compiled code, build scripts, and NodeJS modules. Inside the src directory, create an index.html file:

<title>TypeScript Sample for DotComIt Article</title>
<script src="sample.min.js"></script>

This is a simple index.html file. There is one item I want to draw attention to. The script tag which imports a JavaScript file named sample.min.js. This is the file we will generate from the TypeScript code.

Next, create a file named greeter.ts. The ts extension is the standard extension for TypeScript files, similar to how 'js' is the standard extension for JavaScript files. For this sample I'll put all the files inside the root of the src directory, however in a more complex application, I may categorize the files under a descriptive directory structure.

This is the greeter.ts:

export function sayHello(name: string) {
return `Hello from ${name}`;

This file exports a function named sayHello(). The export is not something you'll commonly see in browser JavaScript, but is used when creating NodeJS Modules. It, basically, says that "This is an API I Want people to use to access code in this file." The sayHello() method has a single parameter, name. The type of the name is specified, something that doesn't happen in JavaScript but adding it allows for type checking at the compiler level. The body of the method returns a string, referencing the name variable inside the string. The syntax is very similar to JavaScript, so learning TypeScript should not be a big hurdle for you to climb.

Now create a file named main.ts. This is the entry point to our application. Back in my school days we'd call the routine that ran the app a main routine, so this is a similar approach. The first thing the main.ts does is import the greeter file:

import { sayHello } from "./greeter";

This makes all the code from the greeter.ts file available to use in the main.ts file. Now, create a showHello() method:

function showHello(name: string) {
document.body.innerHTML = sayHello(name);

This method looks a lot like a JavaScript method definition, the only difference is that the name variable is given a type of string. The code accesses the innerHTML of the web pages body tags and outputs the results of the sayHello method, which will just be a string that says hello from the given name.

Finally, call the showHello() method:


That completes the super simple TypeScript application. I could write a lot about TypeScript, however I wanted this article to focus on the build process of turning TypeScript into a JavaScript web application. As such, I'll leave the JavaScript there. When you finally compile the application, it should look something like this in the browser:

A Basic Compile Script

To compile TypeScript into JavaScript we are going to use NodeJS and a bunch of plugins.

Install and Setup NodeJS

The first step is to install NodeJS if you haven't already. The formal instructions will give you more detailed instructions if you haven't already done so. Then create a generic package.json configuration file. You can run this script:

npm init

And follow the instructions to create a simple package.json. You'll see something like this:

My final package.json is listed below:

"name": "typescriptandgulp",
"version": "1.0.0",
"description": "A sample project to compile TypeScript with Gulp",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
"author": "Jeffry Houser",
"license": "ISC",
"repository": {}

Install Node Modules

Now we want to install some NodeJS plugins. First, we want to make sure Gulp is available. Gulp is the script runner we'll use to execute tasks to run our application. Run this command:

npm install --save-dev gulp

You'll see a screen similar to this:

You can ignore the warnings. Your project directory will now have a node_modules directory.

Next, install the TypeScript plugin:

npm install --save-dev typescript

The NodeJS TypeScript plugin will not be used directly in the gulp script, but is a required dependency:

Next, install browserify. Browserify will combine all the JavaScript files into a single file. We also want tsify installed, a plugin that will allow browserify to compile TypeScript into JavaScript. First, install browserify:

npm install --save-dev browserify

You'll see results like this:

Then install tsify:

npm install --save-dev tsify

Your screen should look like this:

A Gulp stream object is named vinyl and is a virtual file format. To manipulate the output from Browserify with a Gulp script , we'll need to convert Browserify's object to the vinyl format. Thankfully there is a plugin for that, vinyl-source-stream module:

npm install --save-dev vinyl-source-stream

See the console results:

It is a lot of setup, but we should have all the required plugins we need to get started now.

Create the Gulp Task

In the root directory of the project, create a file named gulpfile.js. It is the default Gulp configuration file.

First, load the gulp module:

var gulp = require("gulp");

From there, you can create a gulp task for compiling TypeScript:

gulp.task("buildTS", function () {

This is a blank task that does nothing. It calls the task() method on the gulp object. The task() method has two argument: the name of the task and a function to perform the task. You can execute this task by typing this into your console:

gulp buildTS

You should see something like this:

The task does nothing yet, though. Let's make it do something. Import the rest of the libraries:

var browserify = require("browserify");
var source = require('vinyl-source-stream');
var tsify = require("tsify");

Make sure these libraries are imported outside of the Gulp task. After the library import, still outside the Gulp task, let's define a few variables. The first is something I call appEntry:

var appEntries = ['src/main.ts']

It is an array that contains the main TypeScript file. Browserify will analyze main.ts to find all other files it uses and will do recursively. This is a bit different than the process I used in an AngularJS JavaScript application; where I'd process all files ending with the js extension.

Next, create a variable for the processed file name, and one for the final path:

var javaScriptDestinationFile = 'sample.min.js';
var destinationPath = 'build';

The destination file is the final output after the TypeScript files are merged and compiled into a single one. We referenced this file name in the index.html document. The second variable specifies the final destination of the file. I could define these as part of the Gulp task, but prefer to define them as global variables so they are easily accessible across multiple tasks, and I can tweak how everything works just by changing the config values. Now go back inside the buildTS task and call the browserify() method:

return browserify({
compilerOptions: {
module: "commonjs",
target: "es5",
entries: appEntries

This calls the browserify() method and passes in an argument. The argument object specifies the configuration for this browserify process. Let's go through them:

  • compilerOptions: This is another object that specifies how the TypeScript compiler will work.
    • module: Specifies how modules are loaded in UI code, in this case we are using the commonjs convention.
    • target: Specifies the ECMAScript version you want to output to; in this case I am specifying EcmaScript 5, however other versions are supported.
  • entries: Specifies an array of entry points to your application.

This is a very simple config, and it can be a lot more complicated if you need it to be. Next, tell Browserify to compile the TypeScript code:


Each successive command is daisy chained on the other with the dot syntax. This uses the Browserify plugin() method to call the tsify package to compile the TypeScript code into JavaScript.

Next, call bundle() to merge all code into a single unit:


This one is simple. Then, specify the name of the new file:


This uses the vinyl-source-stream module to turn the javaScriptDestinationFile name into something that can be accessed via Gulp. The pipe() method means that we are getting ready to output information, instead of processing input. Finally, specify the destination of the new file:


This uses the pipe() operator too; and the value is Gulp's dest() function. This, basically, tells the script to put all our files in the build directory.

You can run the gulp script:

Look at the directory structure after our first run:

All the node modules we installed are in the node_modules directory. The source we looked at earlier is in the src directory. The JavaScript file built from the TypeScript files is in the build directory. The gulpfile.js and package.json are in the root application directory. I like this structure because it cleanly separates concerns.

Things are not yet runnable in a browser, because the Index.html was not moved from the src directory to the build directory. For the sake of this article, you can move it manually. Runt he code in the browser, and you should see this:

This isn't an interesting app, but it does prove that Gulp is successfully compiling TypeScript and copying the HTML files from the source directory into the build directory.

What's Next?

The next article in this blog series will focus on how to write a Gulp Script that will watch for any changes to your TypeScript files, and re-compile them as you change code.

If you want a more in depth tutorial, sign up to get our full 30 page white paper on building TypeScript applications with Gulp.

Yes, I want to get your white paper on building TypeScript applications

All Content Copyright 2005, 2006, 2007, 2008, 2009 Jeffry Houser. May not be reused without permission
BlogCFC was created by Raymond Camden. This blog is running version