Introduction to TypeScript Language and Tooling

by on January 7, 2013 12:00 am

TypeScript, Microsoft’s new open source JavaScript derivative, brings static typing along with a number of conventional OOP features to the Wild West of JavaScript. Much like CoffeeScript, this syntactical cousin of Ruby and Python compiles to plain old JavaScript. However, unlike CoffeeScript, TypeScript is in fact a superset of the JavaScript language. What this means is that you can actually write vanilla JavaScript in TypeScript (which is cool).

Language Basics

Static Typing – Hello World

Here’s a simple example of TypeScript’s static typing:

function greet(name:string, times:number, el:HTMLElement) {
    var message: string = "";
    for (var i = 0; i < times; i++) {
        message += "Hello, " + name;
    }
    el.innerHTML = message;
}
greet("Bob", 3, document.getElementById('content'));

If we try to pass our greet function parameters of the incorrect type, TypeScript won’t compile:

greet("Bob", "not a number", document.getElementById('content'));

Object Orientation

In my honest opinion, the greatest strength of TypeScript is its introduction of classic OO constructs like classes and inheritance. Granted, these sorts of things can be done in JavaScript’s prototypical system (see David Pitt’s blog post on the subject), but it tends to be more verbose, a bit confusing and far from elegant. In fact, it is so unwieldy that some popular libraries such as MooTools and Backbone provide their own OO abstractions to shield the common developer from the gritty realities of prototypical inheritance.

TypeScript provides the kind of OO goodies that developers over the past twenty years have come to expect. This can be very useful in helping ease developers coming from a conventional OO background into the wild and wonderful world of JavaScript and prototypical inheritance. Look at the following example of a simple class:

class Animal {
    name: string;
    constructor(name: string) {
        this.name = name;
    }
    sayHello() {
        alert("Hello, my name is " + this.name);
    }
}

This compiles to the following JavaScript:

var Animal = (function () {
    function Animal(name) {
        this.name = name;
    }
    Animal.prototype.sayHello = function () {
        alert("Hello, my name is " + this.name);
    };
    return Animal;
})();

Here we can see that although TypeScript appears to follow a more traditional OOP paradigm, under the covers all it really does is add some syntactic sugar to JavaScript’s basic prototypical inheritance model.

Inheritance

Let’s look at a simple example of one of the most useful of all OO paradigms (and my personal favorite) – Inheritance.

class Animal {
    name: string;
    constructor(name: string) {
        this.name = name;
    }
    sayHello() {
        alert("Hello, my name is " + this.name);
    }
}

class Pony extends Animal {
    sayHello() {
        super.sayHello();
        alert("and I am a pony!");
    }
}

var pony: Pony = new Pony("George");
pony.sayHello();

Pretty cool! I won’t show you what this compiles to here (it’s ugly), but if you’re curious, copy this into Microsoft’s online TypeScript Playground to get a better feel for how TypeScript compilation works.

Plain JavaScript in TypeScript

Although TypeScript allows you to use static typing, at any point in development you are free to fall back to writing vanilla JavaScript. For instance, our original greet method example from earlier could have been written in plain JS:

function greet(name, times, el) {
    var message = "";
    for (var i = 0; i < times; i++) {
        message += "Hello, " + name;
    }
    el.innerHTML = message;
}

Modularization and multi-file

TypeScript provides built-in support for CommonJS and AMD modules. It is quite simple to import and export TypeScript files, just like you would in a server-side language. Importing JavaScript libraries is a bit trickier, but can still be done. I will cover more on this in a later blog post dedicated to the topic, so stay tuned!

Tooling

TypeScript was created by Microsoft, so as you’d expect, the first major IDE to have support for it is Visual Studio 2012. They have a nice plugin that integrates the TypeScript compiler into the IDE. Note that this download includes the TypeScript compiler, which can be run from the command line, as well as the VS plugin (VS 2012 must already be installed when the plugin is installed in order for the IDE to include TypeScript support).

As far as support goes with other IDEs, the current landscape is a bit sparse. WebStorm (my personal favorite web IDE, created by the people who brought you IntelliJ) has support coming in version 6, currently only available in the Early Access Program. There does not seem to be a solid Eclipse plugin yet. There appear to be some offerings available for Sublime Text, emacs and vim.

At the moment, the clear frontrunner – as you might expect – is Visual Studio. Let’s look at what it has to offer.

Visual Studio 2012

You can create a new TypeScript project by selecting “HTML Application with TypeScript.”

This creates a basic project that includes a default.html that loads app.js, the compiled result of app.ts, the main TypeScript file:

Running in Browser

Building our solution uses the TypeScript compiler to generate an app.js output file. To run, we can select what browser we want to use. Like any level-headed developer, I choose Chrome.

Selecting this option opens up a new tab in Chrome running our app:

Debugging

We have two options to debug in Chrome developer tools: debug the compiled JavaScript output, or use source maps to debug our TypeScript files. The first option is simple enough – we just open our developer tools, open up app.js and start setting breakpoints.

Source maps are a bit different. If you’re not familiar with the concept, you can read about it here. Basically, source maps map the compiled, possibly minified code that the browser sees onto the actual source code you wrote, with all its syntactic niceties. This, of course, makes debugging much easier. In TypeScript, adding the -sourcemap switch on compilation generates sourcemap information in the compiled output. Visual Studio adds this option by default, so we don’t have to worry about it here.

To use source maps in Chrome, you must enable the source maps option:

This gives us the option to load app.ts and view our TypeScript code:

These debugging capabilities make real TypeScript development much more practical.

IntelliSense

One of the biggest benefits that comes with using TypeScript is the ability to use powerful IntelliSense. With plain JavaScript’s dynamic typing, it is quite difficult for IDEs to offer safe, clean and reliable IntelliSense capabilities (WebStorm does it the best, in my opinion). With TypeScript, you can rely on such useful operations as Renaming a method or class. This is something very hit-or-miss in pure JS, and will be a great boon when developing large-scale applications.

Takeaway/First Impressions

What to make of TypeScript? The reaction to TypeScript’s release has ranged from dismissive to enthusiastic. Naturally, opponents of static typing dismiss it as an unholy pollution of JavaScript’s type-agnostic purity, whereas fans of compiled languages have great praise for it. Those who are critical of Object Orientation generally will not be impressed, while adherents will be excited to finally have OO available to them in the browser.

My take: it depends on you and your use case.

If you are working on a simple, lightweight web application with no more than a handful of developers, the overhead of compilation and learning new language features will probably not be worth the cost in flexibility and speed of development. You won’t like it.

If, on the other hand, you are working on a large-scale Enterprise application with multiple teams and dozens of developers, TypeScript could very well be the tool that makes a JavaScript-based application feasible. There is a certain degree of safety and stability to be found in static typing, and OO certainly helps prevent repetitive coding tasks. If your developers are all JavaScript gurus with years of experience on the client, you probably don’t need TypeScript. If you have a gaggle of Java/C# guys, TypeScript could be huge for you.

So should you invest in TypeScript? Again, it depends on your team and your project.

I’ll add a final caveat – TypeScript is very new right now. It could be a big risk for an organization to take a leap with TypeScript this early in the game. It certainly helps that a giant like Microsoft is behind it, but it remains to be seen if TypeScript will be a long-lived platform. I would certainly advise caution at this point.

In my next post, I will be examining TypeScript’s modularization techniques and how existing JavaScript libraries can be leveraged, so stay tuned!

Brett Jones, asktheteam@keyholesoftware.com

I would also be honored if you would follow me on Twitter – @brettjonesdev.

  • Share:

7 Responses to “Introduction to TypeScript Language and Tooling”

  1. Very nice intro to TypeScript. I’ll add that it’s fully compliant with EcmaScript 6 and new additions/subtractions to EcmaScript can break the code in future Typescript releases, making it a bit risky to be used in developing huge apps in this moment.

    I still think that coffeescript is a better choice for people with python/ruby background, but typescript has features which are more suited to developing large apps. This is mainly how javascript is going to look in 1-2 years (probably excluding the static typing).

    • Brett Jones says:

      Thanks! Good point on EcmaScript compliance issue. The “class” construct which is coming is really almost identical to the way TypeScript compiles. It will be interesting to see how TypeScript matures – I can definitely see it becoming the Java of client-side web apps for the enterprise.

  2. Nice post! Lots of great detail here!

  3. Phil says:

    Nice, Brett. I was a lot more dismissive about TypeScript until I read this.

  4. [...] Introduction to TypeScript Language and Tooling – The Keyhole Software blog takes a brief look at the TypeScript language and the Visual Studio 2012 tooling support for TypeScript. [...]

  5. [...] my last post, I introduced TypeScript, Microsoft’s new offering which layers static typing on top of [...]

  6. [...] article first appeared on Keyhole Software’s blog. Stay tuned for more of the latest in tech for [...]

Leave a Reply

Things Twitter is Talking About
  • Have you read @wdpitt's newest book? - Web Essentials using #JavaScript & #HTML5. Free PDF download via @InfoQ: http://t.co/lesuPJ770I
    August 20, 2014 at 2:31 PM
  • How can we ensure that we write unit tests with sufficient coverage? Here are some tips for success in #unittesting - http://t.co/zqytilzXXW
    August 20, 2014 at 11:31 AM
  • RT @DZoneLinks: Easily Boost your Web Application by Using nginx - Compuware APM Blog - http://t.co/wm26pvCyKm - @DZoneLinks Big Link by ha…
    August 20, 2014 at 8:59 AM
  • Interested in @unity3d? Check out @johnwboardman's tutorials for Unity game dev with #JavaScript & C#: http://t.co/exsha7cP2b
    August 19, 2014 at 3:30 PM
  • But if you have a passion for quality dev, we might be up your alley. Check out our culture - http://t.co/kWgVdxgvpG http://t.co/y4IFbUA5Ia
    August 19, 2014 at 3:04 PM
  • FRP can solve a common #JavaScript problem - asynchronous requests to the server not returning in requested order http://t.co/jB0ox7Jo4n
    August 19, 2014 at 11:38 AM
  • #RabbitMQ: messaging software built on AMQP protocol. Learn relevant concepts & how to avoid common "gotchas" here: http://t.co/ZwMXlhKyX8
    August 19, 2014 at 9:30 AM
  • We're about to send out our free monthly tech newsletter. Dev tips/articles via email. Not on the list yet? Sign up - http://t.co/aamFVCyyJn
    August 18, 2014 at 1:44 PM
  • There's a new post on the Keyhole blog by Phuong Nguyen - Functional Reactive Programing and #JavaScript - http://t.co/jB0ox7Jo4n
    August 18, 2014 at 11:03 AM
  • Thanks for the RT, @TheGrisExplores! Have a great week.
    August 18, 2014 at 9:38 AM
  • Rapid appdev has a bad rep, but there are ways to bring development time down the right way. Don't Fear the Rapid - http://t.co/aTPcAKOj0r
    August 18, 2014 at 8:31 AM
  • Code For Maintainability So The Next Developer Doesn't Hate You - http://t.co/FWTMF7Pixd 8 helpful tips to do so.
    August 16, 2014 at 12:20 PM
  • DYK? We prefer diverse views, so the info we share doesn't always reflect us as a company. See our Social Policies - http://t.co/MXhB9lE9tV
    August 15, 2014 at 3:30 PM
  • KHS summer intern Bryan Melland just said his goodbyes, headed off to his 1st year @ University of Nebraska. Best wishes for a great year!
    August 15, 2014 at 3:02 PM
  • RT @fpmoles: It's official, KC has a Spring User Group: http://t.co/vaoiGcEva4 cc:@rob_winch
    August 15, 2014 at 2:01 PM
  • Automated Testing is great for dev, but does bring a set of challenges (especially for #agile teams). Success tips: http://t.co/1acl1ngO7i
    August 15, 2014 at 1:20 PM
  • A #JavaScript promise is an I.O.U. to return a value in the future. Promises are cool. Learn about them here - http://t.co/6wCz9b7e4v
    August 15, 2014 at 8:16 AM
  • Found a great resource for folks who want to learn to code - #KC Code Noob. The next Meetup 8/20 covers #Bootstrap - http://t.co/bHom4Lvz7h
    August 14, 2014 at 2:11 PM
  • RT @nicholascloud: the mother of all javascript wysiwyg editor lists https://t.co/o83cGoHQB8
    August 14, 2014 at 11:48 AM
  • If you're a Java dev, you're likely familiar with Annotations. But have you created your own #Java Annotations? Ex - http://t.co/BgCsYjxZKF
    August 14, 2014 at 11:35 AM
Keyhole Software
8900 State Line Road, Suite 455
Leawood, KS 66206
ph: 877-521-7769
© 2014 Keyhole Software, LLC. All rights reserved.