Channels ▼
RSS

Open Source

Working with TypeScript in Visual Studio 2012


In Microsoft TypeScript: The Lay of the Land, I focused on the TypeScript Playground and provided a brief overview of the main goals of TypeScript and its support for types, interfaces, and classes. I explored IntelliSense, autocomplete, syntax, and error highlighting features in TypeScript Playground. The Playground is really useful for easily understanding TypeScript features and how they are translated to plain JavaScript; however, you won't code all your TypeScript files in the Playground.

As an alternative, you can download and install the command-line TypeScript compiler and use it in conjunction with your favorite editor. At the time of writing, the latest TypeScript version is 0.8.3.1, and the only IDE that has a plug-in utilizing the TypeScript language service in the code editor is Visual Studio 2012. The latest TypeScript version with the Visual Studio 2012 plug-in is available for download. Notice that the most current version is in the last row that appears in the "Files in this download" grid; therefore, you have to pay attention to the numbers before clicking on the Download button for the desired version. The grid is a bit confusing and you will want to be careful to download the latest version and not previous versions (see Figure 1). Before you finish the installation of TypeScript for Visual Studio 2012, a dialog box will prompt you to restart your system for the configuration changes to take effect.

downloading TypeScript
Figure 1: The Download center Web page displays a grid with many available versions of TypeScript for Visual Studio 2012.

If you don't work with Visual Studio 2012, you can download the syntax files for the following popular editors:

However, in this article, I focus on using TypesScript in Visual Studio. After installing the software and restarting your system, you will be able to create TypeScript files in Visual Studio 2012. You just need to select File | New | File | Script and select TypeScript File (Figure 2).

Creating a blank TypeScript source file in Visual Studio 2012
Figure 2: Creating a blank TypeScript source file in Visual Studio 2012.

There is also an "HTML Application with TypeScript" project template that you can find in Installed | Templates | Other Languages | TypeScript within the New Project dialog box (Figure 3).

Creating an HTML application with TypeScript in Visual Studio 2012
Figure 3: Creating an HTML application with TypeScript in Visual Studio 2012.

The build action for the TypeScript files (.ts extension) is TypeScriptCompile. Whenever you build a project that includes these files, the TypeScript compiler generates the JavaScript files (.js extension). For example, in an application that uses the "HTML Application with TypeScript" project template, there is an app.ts TypeScript file that generates an app.js JavaScript file when you build the project (Figure 4).

Properties for the app.ts TypeScript file and the generated app.js JavaScript file
Figure 4: Properties for the app.ts TypeScript file and the generated app.js JavaScript file.

If you don't want to build each time you check the generated JavaScript code for your TypeScript files, you can install the Web Essentials 2012 extension and restart Visual Studio 2012. By default, whenever you save a TypeScript file, Web Essentials will automatically compile it and generate the JavaScript file. In addition, Web Essentials 2012 enables a split-screen editor: whenever you edit a TypeScript file, the TypeScript code appears on the left-hand side and the generated JavaScript code on the right-hand side (Figure 5). The split-screen editor is extremely useful when you are learning TypeScript features. Just remember that the JavaScript code will be refreshed whenever you save the file, and not automatically while you're editing the TypeScript file.

Editing a TypeScript file in the split-screen editor
Figure 5: Editing a TypeScript file in the split-screen editor.

Web Essentials 2012 also adds support for regions in TypeScript and allows you to adjust the compiler settings. You just need to select Tools | Options | Web Essentials | TypeScript and change the options according to your needs (see Figure 6). By default, the TypeScript compiler generates EcmaScript 5-compatible code, but you can change the target version to EcmaScript 3. You can also disable the split-screen editor by setting "Show preview window" to False.

Setting the TypeScript compiler options
Figure 6: Setting the TypeScript compiler options with the configuration page that Web Essentials 2012 adds to Visual Studio 2012.

The default path for the TypeScript compiler is Program Files (x86)\Microsoft SDKs\TypeScript. You can execute tsc.exe in the command prompt to generate the JavaScript output from the TypeScript input. If there are any errors, the compiler will display them on the console. For example, the following line generates the AlienSample.js JavaScript file by compiling the AlienSample.ts TypeScript code:

tsc AlienSample.ts

I won't go into all the different compiler options, but you can easily learn about them by executing tsc --help. Also, you can doublecheck the TypeScript version number by executing tsc -v.

Taking Advantage of Member Accessibility

TypeScript allows you to specify the desired accessibility for member declarations: public or private. By default, a member has public accessibility. Private members serve as an indication of intent because JavaScript doesn't provide a mechanism to create private members. You can access private members only within the class body that includes their declaration: Any attempt to access private members outside that class body generates a compile-time error. For example, the following TypeScript code defines damagePower as a private property; therefore, the constructor can access it:

//// TypeScript code
class BadAlien implements Alien {
    private damagePower: number;    

    constructor(public name: string, public angle: number, public bonus: number, public rotationSpeed: number) {
        this.damagePower = 0.1 * bonus;
    }
}

If you write the following lines, the editor and the TypeScript compiler will generate an error in firstBadAlien.damagePower because the property is private. In this case, the error message will be "The property 'damagePower' does not exist on value of type 'BadAlien'."

  var firstBadAlien = new BadAlien("DrDobbsBadAlien", 0, 5000, 5);
  firstBadAlien.damagePower = 10;

Working with Inheritance

TypeScript supports inheritance and overriding. Thus, you can create derived classes that inherit all members from a base class. You can override public members of the base class in the derived class, and use super calls to call either the constructor or other local functions of the base class.

The TypeScript compiler generates JavaScript code that makes calls to some support functions. Thus, inheritance, overriding, and super calls add overhead that you must consider. For example, the following TypeScript lines add a simple increaseSpeed function to the well-known BadAlien class. The new MulticolorBadAlien class extends BadAlien, and therefore, MulticolorBadAlien inherits from BadAlien. MulticolorBadAlien adds an initialColor parameter to the constructor and uses super to call the base constructor with the necessary parameters. MulticolorBadAlien overrides increaseSpeed, uses super to call the increaseSpeed function from the base class, then changes the color for the MulticolorBadAlien.

//// TypeScript code
class BadAlien implements Alien {
    private damagePower: number;    

    constructor(public name: string, public angle: number, public bonus: number, public rotationSpeed: number) {
        this.damagePower = 0.1 * bonus;
    }
    increaseSpeed() { this.rotationSpeed += 1; }
}

class MulticolorBadAlien extends BadAlien {
    private color: string;
    constructor(public name: string, public angle: number, public bonus: number, public rotationSpeed: number, initialColor: string) {
        super(name, angle, bonus, rotationSpeed);
        this.color = initialColor;
    }
    increaseSpeed() {
        super.increaseSpeed();
        if (this.color === "red") {
            this.color = "blue";
        }
        else {
            this.color = "red";
        }
    }
}

The following lines show the JavaScript code that the TypeScript compiler generates:

//// JavaScript code generated by the TypeScript compiler
var __extends = this.__extends || function (d, b) {
    function __() { this.constructor = d; }
    __.prototype = b.prototype;
    d.prototype = new __();
};
var BadAlien = (function () {
    function BadAlien(name, angle, bonus, rotationSpeed) {
        this.name = name;
        this.angle = angle;
        this.bonus = bonus;
        this.rotationSpeed = rotationSpeed;
        this.damagePower = 0.1 * bonus;
    }
    BadAlien.prototype.increaseSpeed = function () {
        this.rotationSpeed += 1;
    };
    return BadAlien;
})();
var MulticolorBadAlien = (function (_super) {
    __extends(MulticolorBadAlien, _super);
    function MulticolorBadAlien(name, angle, bonus, rotationSpeed, initialColor) {
        _super.call(this, name, angle, bonus, rotationSpeed);
        this.name = name;
        this.angle = angle;
        this.bonus = bonus;
        this.rotationSpeed = rotationSpeed;
        this.color = initialColor;
    }
    MulticolorBadAlien.prototype.increaseSpeed = function () {
        _super.prototype.increaseSpeed.call(this);
        if(this.color === "red") {
            this.color = "blue";
        } else {
            this.color = "red";
        }
    };
    return MulticolorBadAlien;
})(BadAlien);

The classes can include either static or instance members. The static keyword allows you to specify that you want a property or a function to be a static member.


Related Reading


More Insights






Currently we allow the following HTML tags in comments:

Single tags

These tags can be used alone and don't need an ending tag.

<br> Defines a single line break

<hr> Defines a horizontal line

Matching tags

These require an ending tag - e.g. <i>italic text</i>

<a> Defines an anchor

<b> Defines bold text

<big> Defines big text

<blockquote> Defines a long quotation

<caption> Defines a table caption

<cite> Defines a citation

<code> Defines computer code text

<em> Defines emphasized text

<fieldset> Defines a border around elements in a form

<h1> This is heading 1

<h2> This is heading 2

<h3> This is heading 3

<h4> This is heading 4

<h5> This is heading 5

<h6> This is heading 6

<i> Defines italic text

<p> Defines a paragraph

<pre> Defines preformatted text

<q> Defines a short quotation

<samp> Defines sample computer code text

<small> Defines small text

<span> Defines a section in a document

<s> Defines strikethrough text

<strike> Defines strikethrough text

<strong> Defines strong text

<sub> Defines subscripted text

<sup> Defines superscripted text

<u> Defines underlined text

Dr. Dobb's encourages readers to engage in spirited, healthy debate, including taking us to task. However, Dr. Dobb's moderates all comments posted to our site, and reserves the right to modify or remove any content that it determines to be derogatory, offensive, inflammatory, vulgar, irrelevant/off-topic, racist or obvious marketing or spam. Dr. Dobb's further reserves the right to disable the profile of any commenter participating in said activities.

 
Disqus Tips To upload an avatar photo, first complete your Disqus profile. | View the list of supported HTML tags you can use to style comments. | Please read our commenting policy.
 

Video