Build Enterprise-Scale JavaScript Applications with TypeScript

Microsoft's TypeScript can help you create more reusable and maintainable JavaScript code

What is in this article?:

  • Build Enterprise-Scale JavaScript Applications with TypeScript

Web application technologies continue to move forward at a bristling pace -- and many of them based on HTML5 and/or JavaScript. As more and more HTML5 technologies are integrated into browsers, the amount of JavaScript that's required to support applications increases significantly. Technologies such as geolocation, local storage, canvas, web workers, WebSockets, and many others rely heavily on JavaScript. In addition to HTML5 technologies, the popularity of single-page applications, Ajax, Node.js, and other JavaScript frameworks continues to push JavaScript forward and make it increasingly more relevant to developers.

The ever-increasing usage of JavaScript code in applications makes reuse, maintainability, bugs, and other related areas crucial. This is especially true for enterprise-scale applications that could have thousands of lines of JavaScript code. Fortunately, developers have options for streamlining their JavaScript coding -- for example, by using any of several different JavaScript patterns, such as the Revealing Module Pattern and the Revealing Prototype Pattern, to structure code, and ECMAScript 6 will offer increased modularity in the future. However, ensuring that correct types (e.g., strings, numbers, Booleans) are being passed between functions can be tricky unless you add to the application robust unit tests using test frameworks such as QUnit or Jasmine. It goes without saying, though, that it would certainly be helpful to be able to structure code more easily and catch type issues up front.

To help developers who are writing "application-scale" JavaScript applications, Microsoft has released a new language called TypeScript, which addresses the aforementioned areas that can be problematic for JavaScript-based enterprise application development. Here I will introduce the fundamentals of TypeScript, describe the benefits it offers, and show how you can use TypeScript to generate JavaScript code. I'll also talk about how TypeScript can be used in several different editors, to give you code help and syntax highlighting.

Before jumping in, you should be aware that although TypeScript has several great features, it's definitely not for everyone or every project. The goal of this article isn't to convince you to use TypeScript instead of standard JavaScript. Throughout the article I'll describe different features that TypeScript offers and let you decide whether or not TypeScript is a good fit for your applications.

What Is TypeScript?

TypeScript was created by Anders Hejlsberg (the creator of the C# language) and his team at Microsoft. In a nutshell, TypeScript is a new language that can be compiled to JavaScript much like alternatives such as CoffeeScript or Dart. Here's the official definition from the TypeScript website: "TypeScript is a language for application-scale JavaScript development. TypeScript is a typed superset of JavaScript that compiles to plain JavaScript. Any browser. Any host. Any OS. Open Source."

One of the best things about TypeScript is that it is a "superset" of JavaScript. It isn't a standalone language completely separated from JavaScript's roots. This means that you can place standard JavaScript code in a TypeScript file (a file with a .ts extension) and use it directly, which is important given all the existing JavaScript frameworks and files. Once a TypeScript file is saved, it can be compiled to JavaScript using TypeScript's tsc.exe compiler tool.

So what are some of the key features of TypeScript? First, TypeScript is built upon JavaScript, which makes it very easy for a developer to start using the language. Second, TypeScript provides built-in type support, meaning that you define variables and function parameters as being "string", "number", "bool", and others to avoid incorrect types being assigned to variables or passed to functions. Third, TypeScript provides a way to write more modular code by directly supporting class and module definitions, and it even provides support for custom interfaces. Finally, TypeScript integrates with several different tools, such as Visual Studio, Sublime Text, Emacs, and vi, to provide syntax highlighting, code help, build support, and more, depending on the editor.

Not only does TypeScript provide excellent tool support, you can also use TypeScript with existing JavaScript frameworks, such as Node.js and jQuery, and even catch type issues and provide enhanced code help. Special "declaration" files that have a d.ts extension are available for Node.js, jQuery, and other libraries out of the box. Visit the TypeScript page on CodePlex for an example of a jQuery TypeScript declaration file that can be used with tools such as Visual Studio 2012 to provide additional code help and ensure that a string isn't passed to a parameter that expects a number. Although declaration files certainly aren't required, TypeScript's support for declaration files makes it easier for you to catch problems up front while working with existing libraries such as jQuery. In the future, I expect TypeScript declaration files will be released for different HTML5 APIs, such as canvas, localStorage, and others.

Getting Started with TypeScript

One of the best ways to get started learning TypeScript is to visit the TypeScript Playground. The playground provides a way to experiment with TypeScript code, get code help as you type, and see the JavaScript that TypeScript generates once the TypeScript code is compiled. Figure 1 shows an example of the TypeScript Playground in action.

144666_fig1_typescript_playground-sm
Figure 1: The TypeScript Playground

One of the first things that might stand out to you about the code shown in Figure 1 is that classes can be defined in TypeScript. This makes it easy to group related variables and functions into a container, which helps tremendously with reuse and maintainability, especially in enterprise-scale JavaScript applications. Although you can certainly simulate classes using JavaScript patterns (note that ECMAScript 6 will support classes directly), TypeScript makes the task of defining classes quite easy, especially for developers who come from an object-oriented programming background.

As an example, let's look at the Greeter class in Listing 1, which is defined using TypeScript.

Listing 1: A Greeter Class Written in TypeScript

class Greeter {
    greeting: string;
    constructor (message: string) {
        this.greeting = message;
    }
    greet() {
        return "Hello, " + this.greeting;
    }
}  


Looking through the code, you'll notice that static types can be defined on variables and parameters (e.g., greeting: string), that constructors can be defined, and that functions can be defined -- for example, greet(). The ability to define static types is a key feature of TypeScript (and where its name comes from) and one that can help you identify bugs before even running the code. TypeScript supports many types, including primitive types such as string, number, bool, undefined, and null, as well as object literals and more complex types such as HTMLInputElement (for an <input> tag). Custom types can be defined as well.

The JavaScript output generated by the TypeScript class in Listing 1 is shown in Listing 2.

Listing 2: JavaScript Generated from Compiling a TypeScript File

var Greeter = (function () {
    function Greeter(message) {
        this.greeting = message;
    }
    Greeter.prototype.greet = function () {
        return "Hello, " + this.greeting;
    };
    return Greeter;
})();


Notice in the output the use of JavaScript prototyping and closures to simulate a Greeter class in JavaScript. The body of the code is wrapped with a self-invoking function to remove the variables and functions from the global JavaScript scope. This is an important feature that helps you avoid naming collisions between variables and functions.
 ยป

Please or Register to post comments.

Upcoming Training

Testing with Visual Studio 2012

Join Brian Minisi for this 3-session online event. You'll learn The importance of testing is undeniable in the overall application lifecycle. We have all been in projects where testing is inadequate. The result is significant effort and cost to fix bugs that are introduced into production; not to mention the cost of a damaged reputation.

EARLY BIRD PRICING NOW!

Register Now

Featured Products