CHAPTER 1

image

Getting Up to Speed with TypeScript

In this chapter, you’ll start your look at TypeScript with an overview and an example. In particular, this chapter covers the following:

  • The motivation for the TypeScript project
  • What TypeScript does and what it doesn’t do compared to JavaScript and other JavaScript-related languages
  • How to install it and what you get as a result
  • A simple example using TypeScript and Visual Studio

Hopefully, by the end of this chapter, you’ll have a good idea of what TypeScript does and how. You’ll follow this up in Chapter 2 by looking in depth at the many new language features of TypeScript, and in Chapter 3 by learning how to incorporate TypeScript into some projects as a whole.

The Development of TypeScript

JavaScript probably should not have been the first choice for the language of all Web functionality—at least, not without some serious reworking. It became standardized long before it was ever rationalized. And had rationality been the goal, it should have looked much more like Java than script.

Scott M. Fulton, ReadWrite

http://readwrite.com/2012/10/03/microsofts-typescript-fills-a-long-standing-void-in-javascript

Stop. Before you read any further, open a browser, load the home page for Google or Bing, and then view the source code for the page. It’s just a mass of minimized JavaScript. Would you like to figure out how the page works by looking at the source code? No. Me neither.

JavaScript is an unusual beast. When it was first introduced in late 1995 to give a web page some dynamism, neither the browsers nor the browser vendors were ready. It arrived during the first skirmishes of the browser wars. Each browser had its own Document Object Model and its own Browser Object Model, and they were still changing. Trying to keep even some basic functionality on a web page compatible across browsers was a nightmare and required far more code than it should have. Microsoft first tried to get us to script pages by using VBScript and then caused confusion with JScript, its own version of the language. Oh, and all the JavaScript execution engines were pretty woeful. Even the name of the standard for JavaScript had to be changed to ECMAScript because Sun Microsystems wouldn’t let the standards body use the name.

A little messy, wasn’t it?

Fortunately, common sense has prevailed over time. Browsers now generally follow web standards, their Document Object Models are nearly all implemented in the same way, and modern JavaScript execution engines such as V8 in Google Chrome and Chakra in Microsoft Internet Explorer are exponentially quicker than their predecessors. JavaScript itself has come a long way as well. Five editions of ECMAScript have been published, and a sixth, code-named Harmony, is under development. The popularization of object-oriented JavaScript, JSON, AJAX, and the HTML5 JavaScript APIs (in that order) have seen its use in serious, nontrivial coding on the client side grow sharply. On the server side, meanwhile, Node.js has shown to the world that JavaScript is a perfectly valid server-side technology, and even Microsoft has been pushing the use of JavaScript as an equivalent to C# and Visual Basic; Windows 8 applications can be built with JavaScript and HTML5 as well as C#/Visual Basic and XAML.

Which brings us to the big question: is JavaScript “big enough” for writing complete applications? JavaScript was never designed to be a language for larger applications. Google has proven it possible, but the fact that it has also created a whole new language—Dart—which can compile down into JavaScript because that’s what we all use but which requires its own virtual machine (currently available only in a developmental build of Chrome) for optimal performance, might indicate just how hard it is and how awkward maintenance can be.  JavaScript does support classical inheritance and other code reuse patterns, but it’s a dynamic language without the features we see in IronPython and IronRuby. It lacks the familiar home comforts of a C# or Visual Basic class-based object-oriented programming model, not to mention strong typing, interfaces, and namespaces, which we might consider the bread and butter of our development efforts. The forthcoming Harmony specification does include these, but ratification is a way off, and it’ll be longer still before browsers include JavaScript engines that support it. There are still engines supporting only v3 of ECMAScript rather than the latest (published in December 2009) v5 in full, for heaven’s sake.

Microsoft has decided that the big answer to the big question is no, and thus has created TypeScript, a superset of JavaScript that includes static typing, classes, interfaces, modules, and a couple of other features that .NET developers will find familiar and that are borrowed from the Harmony specification. We now have at our disposal a way to build large applications in JavaScript (or to switch into application-scale JavaScript development, as Microsoft call it) far more easily than was previously possible. More important, we have a system that makes it easier to scale, debug, and revise applications once written. And, at the heart of it, are four simple truths:

  • TypeScript is just JavaScript. You only need to know JavaScript to use TypeScript, and all your favorite third-party JavaScript libraries (jQuery, MooTools, Prototype, and so forth) will work fine with it.
  • JavaScript is just TypeScript. Any valid .js file can be renamed .ts and be compiled with other TypeScript files.
  • TypeScript borrows from the Harmony specification. When Harmony is ratified, the TypeScript compiler can just let the new language elements alone and allow the new Harmony-compliant engines to parse your TypeScript as pure JavaScript instead.
  • The TypeScript compiler is itself a JavaScript file (compiled down from TypeScript). Thus it can be hosted in any browser, on any host, on any operating system if required. There’s no dedicated VM and no plan to develop one.

Oh, and TypeScript is an open source project too:

  • The compiler is an open source project and released under the Apache 2.0 license.
  • The TypeScript language is available under the Open Web Foundation’s Final Specification Agreement (OWFa 1.0).

All of this means that you can have direct input into bug fixing and new features by submitting bug reports and feature requests on http://typescript.codeplex.com.

What TypeScript Is, Does, and Does Not Do

So yay for Microsoft having the gumption to create and propel TypeScript into a crowded web development world where several efforts to make app-scale development more manageable (Dart  and CoffeeScript, to name two) already exist. But now we’re past the justification for its existence, what exactly does it do, and how does it work? More important, perhaps: what doesn’t it do, exactly?

At its heart, TypeScript has three components:

  • The TypeScript compiler: Written itself in TypeScript, the compiler recompiles TypeScript down to idiomatic JavaScript, compliant to ECMAScript v3 by default or v5 with a compiler switch. The compiler is covered in Chapter 3.
  • The TypeScript Language Service (TLS): The TLS is a Visual Studio extension. It is this extension that provides you with IntelliSense for TypeScript, enforcing type safety and several features of TypeScript within Visual Studio.
  • Declaration files: The TLS uses declaration files (.d.ts files) to provide IntelliSense for the types, function calls, and variables expected by third-party libraries such as jQuery , Prototype, MooTools, and so forth.

You’ll find templates for Visual Studio, sample projects, color-coding rules, and an MSBuild rule as well, but they’re more about enriching the TypeScript development experience rather than enabling it. Understandably, as Microsoft wrote it, you’ll need Visual Studio for the best TypeScript development experience. The TLS is the key. It’s no less valid to write TypeScript outside of Visual Studio, but it is more likely to be prone to errors as the TLS is not there to help you along, writing your code before it goes to the compiler.

WHAT TYPESCRIPT IS NOT

The important thing to remember is that TypeScript is just a tool to be used at coding-time to improve the quality of your JavaScript. After your TypeScript is compiled to JavaScript, you can use all your other tools—minifiers, packagers, runtime loaders, unit test frameworks, and so forth—as you would if you had written the JavaScript from scratch. Microsoft provides some basic support for editing TypeScript from Sublime Text 2, Vim and eMacs, but it does not include the TLS, so there is no IntelliSense or feature enforcement. On the third-party front, JetBrains has announced TypeScript support in WebStorm v6, making this the first cross-platform IDE to do so. There are also several preliminary discussions about supporting it in MonoDevelop.

image Note  Please don’t forget that TypeScript is still only a prerelease (v0.8.1.1 at the time of this writing). The level of TypeScript support for non–Visual Studio IDEs will change.

The TypeScript compiler is also available as a Node.js package, but it is not exposed as an explicit public API for module access. There is a workaround, however (https://github.com/eknkc/typescript-require) while Microsoft works on the official fix (http://typescript.codeplex.com/workitem/97).

TypeScript vs. JavaScript Gotchas

TypeScript’s aims are squarely pointed at the long-term issues of scalability and maintainability, but does it assist with the day-to-day task of writing functional code? JavaScript has more idiomatic programming pain points than most languages, and many online pages are dedicated to listing these gotchas, so you don’t have to figure them out yourself.  Because it is just JavaScript itself, compiled TypeScript is subject to these gotchas as well. However, thanks to the real-time type checking and inference, the TLS does catch a few of these before they get compiled. This section details three of the most common that TypeScript can help to avoid.

Type Coercion Issues

Suppose you have two variables, one a string and the other a number:

var oneNumber = 1;
var oneString = "1";

In JavaScript, you can compare these two variables by using the == operator and expect JavaScript to return true. The == operator coerces one variable into the same type as the other and then compares the two:

var theSameJS = (oneNumber == oneString);  // true in JavaScript. Invalid in TypeScript

In TypeScript, the same operation will not compile until one of the two variables is explicitly cast to the other’s type. Even if the types of oneNumber and oneString are not specifically set, the TLS will infer them from the values assigned, meaning this gotcha is one you shouldn’t need to worry about.

var theSameTS = (oneNumber.toString() == oneString);  // true in TypeScript and JavaScript.

A similar gotcha occurs when using the + operator. If one of the operands is a string, JavaScript will always concatenate the two values together and return a string, rather than adding the two as numbers and returning a number, which may have been the desired result.

var thisIsAString = 1 + "1";  // returns "11"
var thisIsANumber = 1 + parseInt("1", 10);  // returns 2

The TLS won’t stop you from making the same mistake, but it will infer the type of the returned value and flag potential errors later if you reuse it. If you hover the cursor over the name of the variable, the TLSwill display the inferred type of the variable as well.

Block Scope

TypeScript inherits JavaScript’s lack of block scoping for variables. Consider the following (contrived) code:

for (var i = 0; i < 10; i++) {
    console.log(i);  // displays numbers 0 to 9
}
//  variable i now redeclared but value not reset to undefined.
// instead it uses last set value of 9 from inside the for loop block
var i;
console.log(i);  // displays 10

When i is declared, it will remain in scope after the loop exits, so the console will display 10 as well as 0–9. The TLS won’t stop this from happening, but it will infer that i is of type number or type any when it is redeclared because of its previous use as a number in the for loop. Therefore, should i be assigned or inferred a type other than number or any outside of the for loop, the code as a whole will not compile because the code inside the for loop—specifically, the part where i is treated as a number—is then invalid.

Optional Semicolons and Bracket Placement

For C# programmers, the idea that you need not use semicolons to indicate the end of a statement may seem anathema. Likewise, if you press Ctrl+K, D enough times in Visual Studio, it may start to seem odd if the curly braces in your code aren’t on their own lines. So consider this particular code and ask yourself what the function returns:

function optionalSemicolons() {
    return
    {
        a: "Hello"
    };
}

In fact, this function returns undefined because JavaScript interprets the code by adding a semicolon immediately after the return statement. If the opening curly brace is placed next to the return keyword, the function returns an object as expected.

function optionalSemicolons2() {
    return {
        a: "Hello"
    };
}

All of this means that both C# and Visual Basic programmers need to take care when adding semicolons and new lines into code. Fortunately, the TLS can save us some head-scratching in two ways here.

The TLS, together with the Web Essentials extension for Visual Studio, will display your TypeScript code recompiled into JavaScript in the right-hand pane of your Visual Studio window whenever you save your TypeScript file. The compiled version of optionalSemicolons() shows the inserted semicolons (there are actually two of them) not where you’d want them to be.

function optionalSemicolons() {
    return;
 {
        a:
"Hello"
    }
    ; ;
}

The compiled version of optionalSemicolons2(), however, is exactly the same as the TypeScript original.

  • You can also explicitly define the return type of the function. In this case, the function returns an object, so we can rewrite the first line of our errant function as
function optionalSemicolons() : Object { ...

and the TLS will instantly underline the whole function with red squigglies as it does not return an object. Adding the same explicit return type to optionalSemicolons2() will result in no change.

image Note  Full details of TypeScript’s strong typing and function signature syntax can be found in Chapter 2.

TypeScript vs. Other Compile-to-JavaScript Languages

So TypeScript does help with the quality of the JavaScript you can produce as well as its overall structure, but there’s plenty of competition in the particular space. Several dozen similar language projects are listed at https://github.com/jashkenas/coffee-script/wiki/List-of-languages-that-compile-to-JS, for example. How does TypeScript stack up against them all, and is it right for you? Let’s start by asking a few questions:

  • What’s the main aim of the language?
  • Is it still JavaScript, or something else?
  • Does it add static typing?
  • Does it add a class-based, object-oriented programming model?
  • Can I use third-party JavaScript libraries?
  • Is it supported in Visual Studio or Windows?
  • Is it supported on Mac OS or Linux?
  • What VM does it use to run?

First we’ll answer for TypeScript and then for the two most visible alternatives to TypeScript at the moment: Dart and CoffeeScript.

  • The main aim of TypeScript is to enable large-scale application development with JavaScript.
  • TypeScript is a superset of JavaScript, so yes, it is still JavaScript.
  • Yes, TypeScript incorporates static typing.
  • Yes, TypeScript adds a class-based, object-oriented programming model.
  • Yes, but you’ll need a declaration file for the library to enable IntelliSense and strong typing.
  • Yes, with the TypeScript Language Service extension.
  • No concrete IDE support yet for Mac OS or Linux, although the compiler itself is easy to install by itself or in Node.js.
  • It uses the JavaScript VM.

Dart (www.dartlang.org) is Google’s answer to JavaScript. This completely new language addresses JavaScript’s issues, cleans up its semantics, adds static types (as does TypeScript) and class-based object-oriented features, and improves startup times and performance overall. It requires its own Dart VM (currently available only in a developmental build of Chrome) for optimal performance but does come with a Dart-to-JavaScript compiler. It shares some common goals with TypeScript—the main one is making large-scale web application development possible—but in general, the two are separate, with only the dart2js compiler linking the two languages.

  • The main aim of Dart is to learn from the mistakes of JavaScript and provide an alternative.
  • No, it’s a new language but it compiles to JavaScript.
  • Yes, Dart incorporates static typing.
  • Yes, Dart adds a class-based, object-oriented programing model.
  • Not yet, although there is a js-interop library.
  • The Dart Editor IDE is available for Windows, Mac OS, and Linux.
  • Dart has its own VM, but when you compile it to JavaScript, you can run it in any JavaScript VM.

CoffeeScript (http://coffeescript.org), meanwhile, tries not to replace JavaScript but to produce a syntax based on other dynamic languages. This  makes CoffeeScript easier and quicker to write, as it then compiles into neat, well-formed JavaScript. Essentially, you could say it’s JavaScript without the large numbers of braces, brackets, and parentheses, but that would be missing the point. It sits in your tool chain at the same point as TypeScript but helps you generate better JavaScript while using a non-JavaScript syntax.

  • The main aim of CoffeeScript is to provide a language that has neater syntax than JavaScript (based on Ruby and Python) but that compiles back into JavaScript.
  • No, it’s a different language, but like TypeScript, it’s a design-time-only construct to help you write better JavaScript.
  • No, CoffeeScript does not add static typing.
  • Yes, CoffeeScript adds a class-based, object-oriented programming model.
  • You can use external JavaScript libraries from inside CoffeeScript, but you’ll get syntax errors if you compile JavaScript as is, without converting it.
  • CoffeeScript is supported via the Web Extensions add-in for Visual Studio. There are also several other Windows IDEs that support CoffeeScript development.
  • CoffeeScript is available as a Node.js package and via APT for Linux and Mac. Eclipse, Vim, TextMate, and many other IDEs support CoffeeScript.
  • CoffeeScript compiles down to JavaScript, so all you need is a JavaScript VM.

TypeScript vs. ECMAScript

The final question in this section is how TypeScript may evolve as we continue to use it. It is an open source project, so we know that Microsoft will be listening to feature requests as well as taking on bug patches, but we also know that it is trying hard to keep its “additional features” aligned with the ECMAScript 6 standard. For example, the class, module, and arrow function syntax conform to this proposed future standard.

Going one further, it has been stated that,

In the long term, we expect TypeScript to include everything that becomes part of future versions of ECMAScript. In some cases, these will only be available when targeting newer browsers, when the feature relies upon some new runtime capability. But in many cases, where the features are just syntactic sugar, we expect to be able to compile to simple and clean JavaScript for ES3/ES5, which implements a very good approximation.

http://TypeScript.codeplex.com/workitem/15

Looking at the spec as it stands ( http://wiki.ecmascript.org/doku.php?id=&idx=harmony), there’s quite a lot to keep the project busy for several major version releases. What’s not clear, however, is how Microsoft will react if ECMAScript 6 is altered such that realigning TypeScript with the new syntax would create breaking changes across all existing TypeScript projects. Time will tell.

Installation

Now that we’ve established what TypeScript is, what it does, and what it doesn’t do, let’s get cracking and install it. TypeScript has a couple of homes on the Internet:

  • typescriptlang.org is its official home. Here you’ll find the latest bits to download, tutorials, and links to the main help forums.
  • typescript.codeplex.org is where you’ll find the latest source code for the TypeScript compiler, along with a list of open bugs and more discussion forums.

You’ll be concentrating on setting up a TypeScript development environment here rather than working with nightly builds of the compiler. There are two environments you’ll see how to build:

  • Visual Studio 2012
  • Sublime Text 2

image Note  You’ll also find links on typescriptlang.org to syntax highlighter files for Vim and eMacs.

Visual Studio 2012

Microsoft has focused on giving TypeScript developers the best experience through the non-Express editions of their Visual Studio IDE. In this section, you’ll see how to integrate TypeScript as best as currently allows for work in Visual Studio Professional, Premium, or Ultimate. You’ll find notes about using TypeScript with Visual Studio 2012 Express editions and WebMatrix afterward.

Installing the Compiler and TLS Extension

Assuming you already have Visual Studio 2012 installed, the first task is to install the TypeScript plug-in:

  1. Open a browser at www.typescriptlang.org/#Download.
  2. When it loads, click the link to Download the Plugin for Visual Studio 2012. Currently this points to www.microsoft.com/en-gb/download/details.aspx?id=34790.
  3. Download the installer file TypeScriptSetup.<VERSION>.msi and double-click to install it.

When the installer has finished, open Windows Explorer. Then do one of the following:

  • If you’re running 64-bit Windows, browse to C:Program Files (x86)Microsoft SDKsTypeScript<VERSION> to find the installed files.
  • If you’re running 32-bit Windows, browse to C:Program FilesMicrosoft SDKsTypeScript<VERSION>.

Figure 1-1 shows the contents of the directory.

9781430257257_Fig01-01.jpg

Figure 1-1 .  The TypeScript installation directory and its contents

The key files are as follows:

  • tsc.exe is the TypeScript compiler as an executable file.
  • tsc.js is the command-line compiler called by tsc.exe. It contains an options parser and a batch compiler needed for compiling multiple files.
  • typescript.js is the core compiler without the options parser and batch compiler.
  • tschost.dll is the scripting host for the compiler.
  • TypeScriptLanguageService.vsix is the installer file for the Visual Studio TLS extension.
  • lib.d.ts is a TypeScript declarations file containing the type descriptions for the entire Document Object Model and JavaScript standard runtime. The TLS extension uses this file to provide IntelliSense and type checking when coding.

image Note  See Chapter 3 for the various command-line options available for the TypeScript compiler and for more on declarations files.

At this point, you may want to do the following:

  • Check that the installation directory has been added to your PATH environment variable so you can easily run tsc.exe from the shell of your choice.
  • Download some more definitions files for your future use. If you are likely to use some third-party JavaScript libraries in your application (such as jQuery, WinJS, or Node.js), you’ll need these for the TLS extension to provide IntelliSense and type checking in your calls to these libraries.

You can find d.ts files for WinJS, WinRT, and jQuery 1.7 on the TypeScript CodePlex web site. You’ll find them in the source code listings in the typings directory, and also at https://github.com/borisyankov/DefinitelyTyped, along with many others.

The TLS extension adds several new templates and a new build step into Visual Studio:

  • You can find the HTML Application with TypeScript project template listed under Visual C# (not Visual C# image Web) in the New Project dialog box, as shown in Figure 1-2.

9781430257257_Fig01-02.jpg

Figure 1-2 .  Locating the TypeScript project template

  • To add a TypeScript file to an existing project, use the TypeScript File file template listed under Visual C# (not Visual C# image Web) in the New File dialog box, as shown in Figure 1-3.

9781430257257_Fig01-03.jpg

Figure 1-3 .  Locating the TypeScript File file template

When you add a new TypeScript file to your project, Visual Studio will open it automatically and present some sample code, which you’ll need to delete.

image Tip  If you can’t find the templates in Visual Studio, try rerunning the TypeScriptLanguageService.vsix file manually.

The TSL extension also adds a few editing options if you’d like to tweak the way Visual Studio displays your code. From the Tools menu, choose Options. When the Options dialog box appears, expand Text Editor and then TypeScript, as shown in Figure 1-4.

9781430257257_Fig01-04.jpg

Figure 1-4 .  The TypeScript Options dialog box in Visual Studio 2012

Using Web Essentials

An optional but very handy extension for Visual Studio 2012 only is Mads Kristensen’s Web Essentials 2012. His version for VS 2010 does not include TypeScript support.

image Note  Mads Kristensen is the creator of BlogEngine.NET, among other things, and a program manager for the Web Platform and Tools team at Microsoft. You’ll find his blog at http://madskristensen.net.

Web Essentials adds three very useful functions to your TypeScript development process:

  • When you open a TypeScript file, Web Essentials presents it in a split-screen editing panel, as shown in Figure 1-5. The left side contains the TypeScript you are writing, and the right-hand panel automatically updates with the JavaScript that will be generated. By default, this is ECMAScript 5–compliant JavaScript. If you want to compile it as ECMAScript 3–compliant JavaScript, you’ll need to tweak the TypeScriptCompile build action for MSBuild, which is discussed in Chapter 3. Web Essentials will automatically compile the TypeScript file and update the preview as soon as it is saved in Visual Studio.

9781430257257_Fig01-05.jpg

Figure 1-5 .  The split-pane view of a TypeScript file in Visual Studio 2012 with the Web Essentials extension installed

  • Optionally, you can also set Web Essentials to produce a minified version of the generated JavaScript file.
  • Web Essentials will automatically produce source map (.js.map) files for debugging purposes as soon as the .ts file is saved in Visual Studio.

In fact, it’s a regular Swiss army knife for web developers, with features for style sheet, JavaScript, CoffeeScript, LESS, and JSON development.

Assuming you already have Visual Studio 2012 and the TLS extension installed, you can install Web Essentials 2012 in one of two ways:

  • Using the Extensions and Updates dialog box in Visual Studio itself:
    • a.  From the Tools menu, choose Extensions and Updates.
    • b.  When the dialog box appears, choose Online image Visual Studio Gallery and press Ctrl+E to move to the search box.
    • c.  Type Web Essentials and wait. After a little while, Web Essentials 2012 will appear at the top of the list in the center of the dialog box.
    • d.  Select its entry and then click Download to have it install.
  • Download and install it manually:
    • a.  Open a browser and browse to http://visualstudiogallery.msdn.microsoft.com/.
    • b.  Click in the search box on the right-hand side, type Web Essentials 2012, and press Return.
    • c.  Click the entry for Web Essentials 2012 in the search results list and then click Download on the following page.
    • d.  Double-click the WebEssentials2012.vsix file you’ve just downloaded to install it.

After installing Web Essentials 2012, you can set a number of TypeScript compiler flags to be used by Web Essentials along with a couple of other options from within the Visual Studio Options dialog box. From the Tools menu, choose Options. When the Options dialog box appears, expand Web Essentials and then TypeScript, as shown in Figure 1-6.

9781430257257_Fig01-06.jpg

Figure 1-6 .  TypeScript options for Web Essentials 2012

For more information on the various compiler options, please see “The Compiler” in Chapter 3.

image Note  These compiler options control Web Essentials’ compilation of your TypeScript files across all your projects. Mads Kristensen is currently working with the TypeScript team to come up with a less rigid set of options.

Other Visual Studio Editions

Although it may not be possible to enjoy the full TypeScript experience if you aren’t using Visual Studio 2012 Professional or higher, remember that you can download a current version of the compiler and sample files from http://typescript.codeplex.com and go from there. There are also a few other things you can try.

Visual Studio 2012 Express Editions

The TLS extension for Visual Studio 2012 can be installed successfully into copies of Visual Studio 2012 Express for Web. However, if you have VS 2012 Express for Windows 8 or Windows Desktop installed, the compiler will install successfully, but the TLS extension will not.

The Web Essentials 2012 extension will not install on any Express edition of Visual Studio.

Visual Studio 2010 Professional and Higher

It is apparently possible to install the TLS extension in VS 2010, by installing the compiler as usual and then running the TypeScriptLanguageService.vsix installer manually from the installation directory. Of course, this is not supported by Microsoft.

WebMatrix

Microsoft does not officially provide an extension for the WebMatrix IDE. However, an unofficial extension is already available at http://extensions.webmatrix.com/packages/TypeScript4WebMatrix/. This is an open source extension, the source code for which can be found at http://macawnl.github.com/TypeScript4WebMatrix/.

On Node.js

The TypeScript compiler can be installed as an npm package on Node.js. Just type the following:

npm install -g TypeScript

You’ll be able to compile code by running tsc helloworld.ts, for example.  Note, however, that the compiler itself is not exposed as an instruction, although there is an issue raised in CodePlex to do this (WorkItem 97).

Sublime Text

If you’re not a fan of Visual Studio, you can grab a copy of the TypeScript compiler (either from the CodePlex site or by installing the download) and then run it manually. Sublime Text 2 users can also find a set of TypeScript syntax highlighter rules written by Microsoft at http://blogs.msdn.com/b/interoperability/archive/2012/10/01/sublime-text-vi-emacs-typescript-enabled.aspx.

To install these rules and include TypeScript compilation in your build system, do the following:

  1. Download the Sublime Text zip file from the MSDN Blogs page noted earlier and extract the contents. You’ll find a file inside called typescript.tmlanguage.
  2. Open Sublime Text and from the Preferences menu choose Browse Packages.
  3. When Solution Explorer / Finder opens, create a folder in the current directory called TypeScript and copy the .tmlanguage file into it.
  4. From the Tools menu, choose Build System image New Build System.
  5. Add the following to the new sublime-build file that has been created for you:
    {
        "cmd": ["tsc","$file"],
        "file_regex": "(.*\.ts?)\s\(([0–9]+)\,([0–9]+)\)\:\s(...*?)$",
        "selector": "source.ts",
        "osx": {
           "path": "/usr/local/bin:/opt/local/bin"
        },
        "windows": {
            "cmd": ["tsc.cmd", "$file"]
        }
    }
  6. Restart Sublime Text 2.

From JavaScript to TypeScript

Now that you’ve installed TypeScript, let’s look at a simple example. You’ll take an HTML page with some JavaScript embedded in it and rewrite it as an HTML page backed by some unobtrusive TypeScript. You’ll also see how to add jQuery and some basic structure to the script that might be easier to read coming from .NET.

image Note  The purpose of this exercise is not to learn TypeScript as such, but to illustrate some of the new syntax and how the TLS extension in Visual Studio can help.

Let’s start by creating a new TypeScript project:

  1. Open Visual Studio. From the File menu, choose New Project.
  2. From the Visual C# templates list, select HTML Application with TypeScript and give it the name FirstSteps.
  3. Click OK.

A Simple HTML+JS Page

The project template includes an HTML page backed with a TypeScript file that demonstrates a few more features than we’ll use here, so it will be worth your while coming back to it in a while. In the meantime, you can delete the files app.cs and app.ts.

  1. Press Ctrl+Shift+A, and add a new HTML page to the project called SimplePage.html.
  2. Add the following code:
    <!DOCTYPE html>
    <html>
    <head>
      <title>A Simple Demo</title>
      <script>
        function displayDate() {
          document.getElementById("txtDemo").innerHTML = Date();
        }
      </script>
    </head>
    <body>
      <h1>My First JavaScript</h1>
      <p id="txtDemo">This is a paragraph.</p>
      <button type="button" id="btnGo" onclick="displayDate()">
        Display Date
      </button>
    </body>
    </html>
  3. Press Ctrl+F5 to run this page. You’ll see that the current date and time replaces the paragraph text when you press the button.

TypeScript and IntelliSense

Now it’s time to split out the script from the HTML and rewrite the script as a TypeScript file. The compiler targets only .ts files, so you can’t just embed TypeScript in an HTML page. Here are the steps:

  1. Create a copy of SimplePage.html and rename it SimplePageTS.html.
  2. Delete the <script> block from the <head> element in SimplePageTS.html and also the onclick attribute from the <button> element.
  3. Right-click SimplePageTS.html in Solution Explorer and then click Set as Start Page.
  4. Press Ctrl+Shift+A, and add a new TypeScript file called SimplePage.ts to the project. Delete its contents and add the following, copying the displayDate function verbatim and adding an event handler for the button.
    function displayDate() {
        document.getElementById("txtDemo").innerHTML = Date();
    }
     
    document.getElementById("btnGo").addEventListener("click", displayDate);

    Note that as you type, you get full IntelliSense support for the JavaScript language, the Document Object Model, and any functions you’ve written yourself. Also, if you hover your cursor over a type, function, or variable, you’ll get a full set of information about it, as shown in Figure 1-7.

    9781430257257_Fig01-07.jpg

    Figure 1-7 .  The TypeScript Language Service displays type and method information as you hover

  5. Add a new <script> block as the last child of the <body> element. Set its src attribute to SimplePage.js. This is the JavaScript file our TypeScript will compile into. You could reference the SimplePage.ts file directly here and have it compiled on the fly on the web server, but the performance loss would make this not a particularly viable option.

Errors and Declaration Files

If you run SimplePageTS.html, you’ll see that the page still functions as before, with the TypeScript file being compiled into JavaScript when the site is built. Let’s introduce an error and see what happens.

In SimplePage.ts, change displayDate() to read as follows:

function displayDate() {
    var currentDate: Date = new Date();
    document.getElementById("txtDemo").innerHTML = currentDate;
}

You’ll see that an error is raised, indicating that currentDate cannot be converted to a string (see Figure 1-8). Also, the right-hand pane showing the resultant compiled JavaScript has been grayed out.

9781430257257_Fig01-08.jpg

Figure 1-8 .  TypeScript errors are underscored in the edit window and listed in the Error List window

Why the error? All we did was replace the Date() constructor with a variable containing a Date object. Well, like the gotchas noted earlier, JavaScript silently coerces the Date object into a string in the original example. When we strongly type the currentDate variable as a Date, TypeScript does not allow this conversion to happen implicitly.

In SimplePage.ts, right-click innerHTML and select Go To Definition from the context menu (or press F12). Visual Studio will open the JavaScript runtime and DOM declaration file lib.d.ts and highlight the line showing that the innerHTML property of an HTMLElement object requires a string.

Return to SimplePage.ts and convert currentDate to a string with the following code:

document.getElementById("txtDemo").innerHTML = currentDate.toUTCString();

jQuery, Ambient Declarations, and Reference Hints

At this point, sprinkling a little jQuery into our simple function would make it a little more readable:

  1. In SimplePageTS.html, add a reference to jQuery in the head element.
    <script src="http://code.jquery.com/jquery-latest.js"></script>
  2. In SimplePage.ts, replace the existing code with the following jQuery equivalent:
    function displayDateJQ(): void {
        var currentDate: Date = new Date();
        $("#txtDemo").text(currentDate.toUTCString());
    }
     
    $("#btnGo").click(displayDateJQ);
      

If you try to build the project now, you’ll see that TypeScript raises an issue about the use of the jQuery $ variable. It’s not defined in the .ts file and it hasn’t been declared, so there’s a problem. You’ll also note that there is no IntelliSense for jQuery. There are two solutions to this.

The first is to add an ambient declaration for the $ variable by using the declare keyword at the top of SimplePage.ts.

declare var $: any;

This tells the compiler that $ is a variable of type any and that it is defined in some other (third-party library) JavaScript file, which the site has access to but the compiler does not. The compiler takes it on trust that you know what you’re talking about. The file will compile, and the page will run. But you still don’t get IntelliSense for jQuery.

The second option is to locate a declaration file for jQuery. Like lib.d.ts for the DOM, this will contain all the type information, and class and interface definitions for the jQuery library. The TLS will be able to refer to this, understand from it that $ is a variable of type JQueryStatic, and provide IntelliSense from there.

Add a new folder called lib to your project and add a copy of the latest jQuery declaration file to it. You’ll find it at https://github.com/borisyankov/DefinitelyTyped/tree/master/jquery named jQuery-<version>.d.ts, where <version> is the version you want. At the time of this writing, the version is 1.8.

At the top of SimplePage.ts, add the following reference hint to the compiler. Remove the ambient declaration if you added it earlier.

/// <reference path="libjquery-1.8.d.ts" />

You’ll see that the file now compiles, and the page will run. If you retype some of the function code, you’ll see that you now have IntelliSense for jQuery functions too.

image Note  If you can find a declaration file for the third-party library you are using, make use of it. There is a suggestion on the CodePlex site for a declaration file community site (http://typescript.codeplex.com/workitem/191), but while that is being considered, have a look at https://github.com/borisyankov/DefinitelyTyped for now.

A Little Code Structure with Classes and Modules

In our final revision for this demonstration, you’re going to see how TypeScript’s class and module features can help you refactor your code into a more maintainable structure. As you’ll see in Chapter 2, class and module are roughly analogous to C#’s class and namespace, allowing you to create objects as you would in .NET and give them some scope. In this simple example, adding classes and modules is overkill, of course, but it’s useful to give you a quick flavor of how they work in TypeScript.

1.  In SimplePage.ts, wrap the DisplayDate function inside a class called Chapter1. Note that you’ll need to delete the function keyword preceding DisplayDate, as it is now an object method.

2.  Update the event handler to bind Chapter1.prototype.DisplayDate to the button’s click event, as shown in the following code.

class Chapter1 {

  DisplayDate(): void {

   var currentDate: Date = new Date();

            $("#txtDemo").text(currentDate.toUTCString());

        }

    }

 

$("#btnGo").click(Chapter1.prototype.DisplayDate);

TypeScript includes the ability to make object methods static so we don’t have to go through an object’s prototype to find its method reference for the event handler.

3.  Make DisplayDate a static method by adding the static keyword before its name.

4.  Update the event handler to bind Chapter1.DisplayDate to the button’s click event.

class Chapter1 {

  staticDisplayDate(): void {

   var currentDate: Date = new Date();

            $("#txtDemo").text(currentDate.toUTCString());

        }

    }

 

$("#btnGo").click(Chapter1.DisplayDate);

Finally, we’ll wrap the class in a module. There are two rules to remember for accessing classes from outside the module it is declared in:

  • The class must be made visible by using the export keyword.
  • There’s no equivalent keyword in TypeScript for the using keyword in C#, or imports in Visual Basic. References to the class or static method must be fully qualified with the module and class name.

5.  Wrap the Chapter1 class inside a module called TypeScript.Revealed.

6.  Add the export keyword to the class statement so the event handler can access it.

7.  Update the event handler to reflect the new fully qualified name for DisplayDate.

module TypeScript.Revealed {

    exportclass Chapter1 {

        static DisplayDate(): void {

            var currentDate: Date = new Date();

            $("#txtDemo").text(currentDate.toUTCString());

        }

    }

}

 

$("#btnGo").click(TypeScript.Revealed.Chapter1.DisplayDate );

Once again, you’ll find that the page runs as before. Hopefully, you’ve seen how some of the new features of TypeScript—strong typing, ambient declarations, reference hints, declaration files, classes, and modules—can help you feel more at home creating TypeScript/JavaScript. Now might be a good time to go back to the default.html and app.ts files originally generated with the TypeScript project and review the further syntax features it demonstrates: class member variables and constructors, and lambda (arrow) functions. All of these and more are covered in Chapter 2.

You can find the code for the FirstSteps project in the Source Code/Download area of the Apress web site (www.apress.com).

Summary

JavaScript is in good health, but hasn’t the structure, tooling, or inherent maintainability to be used for application-scale development. Or at least that’s what Microsoft thinks. In this chapter, you’ve taken a wide-angle view of TypeScript—Microsoft’s answer to these problems with JavaScript—and how it works. You’ve seen how to install it and then written your first code with it, using basic syntax features and the TLS service to rewrite some basic JavaScript embedded in a web page into a nicely structured piece of unobtrusive TypeScript.

In the next chapter, you’ll look at the new language features of TypeScript.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.12.163.180