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
  • .@TheGrisExplores: there's a new comment on your Dependency Injection Options for Java blog post - http://t.co/vs897t7bHd (Just FYI :-) )
    September 29, 2014 at 1:48 PM
  • Don't miss Vince Pendergrass' first post on the Keyhole blog - Don’t just randomize, truly randomize! http://t.co/QENl4kGVIs #cryptography
    September 29, 2014 at 9:57 AM
  • .@manohart Thank you for reading! Post author Alok Pandey has answered your question here - http://t.co/Uhn9Bv9L1a
    September 26, 2014 at 11:33 AM
  • Tech Night is now! @zachagardner & @lukewpatterson are presenting to the team on #Docker Code-Along style. Great discussions to be had!
    September 25, 2014 at 5:15 PM
  • Neat - A #JavaScript promise is an I.O.U. to return a value in the future. Here's a quick overview of promises: http://t.co/6wCz9aP4Qn
    September 25, 2014 at 11:35 AM
  • A huge welcome to Matthew Brown who joins the Keyhole team today!
    September 24, 2014 at 4:30 PM
  • RT @darrellpratt: A Journey From Require.js to Browserify http://t.co/t6N7Db1I4A
    September 24, 2014 at 11:54 AM
  • Creating a UI Designer for Quick Development - http://t.co/pNrayNFs5T http://t.co/hvqOaD6Wfq
    September 24, 2014 at 10:40 AM
  • We are under construction! Knocking down walls & expanding our offices in Leawood, KS this week. http://t.co/ph6JElh8lr
    September 23, 2014 at 9:46 AM
  • Did you know? Today in 1986 it was ruled that computer code is protected under copyright law - http://t.co/mCmWPvKOBE
    September 22, 2014 at 4:30 PM
  • Don't miss Alok Pandey's very first post on the Keyhole blog - Creating a UI Designer for Quick Development http://t.co/dWYMCOO3rf
    September 22, 2014 at 2:43 PM
  • If you're a Java dev, you're likely familiar with Annotations. But have you created your own #Java Annotations? Ex - http://t.co/mf1F3eIDY3
    September 21, 2014 at 5:15 PM
  • Check out a quick intro to Functional Reactive Programing and #JavaScript - http://t.co/4LSt6aPJvG
    September 20, 2014 at 11:15 AM
  • In Part 2 of our series on creating your own #Java annotations, learn about processing them with the Reflection API - http://t.co/E1lr3RmjI7
    September 19, 2014 at 12:15 PM
  • The life of a Keyhole consultant - A Delicate Balance: It’s What We Do http://t.co/ToRpWY3aix Blog as true today as the day it was written.
    September 19, 2014 at 9:50 AM
  • 7 Things You Can Do to Become a Better Developer - http://t.co/llPNMUN8nQ
    September 19, 2014 at 8:43 AM
  • .@jessitron Good luck, you'll do great! Our team really enjoyed your KCDC14 talks.
    September 18, 2014 at 10:19 AM
  • RT @woodwardjd: 7 deadly sins of programming. I think I did all of this last week. #strangeloop http://t.co/f7QFq1SpqW
    September 18, 2014 at 10:03 AM
  • In Part 2 of our series on creating your own #Java annotations, learn about processing them with the Reflection API - http://t.co/E1lr3RmjI7
    September 17, 2014 at 3:18 PM
  • We send out our free monthly tech newsletter tomorrow - dev tips/articles via email. Not on the list? Sign up: http://t.co/h8kpjn419s
    September 16, 2014 at 2:58 PM
Keyhole Software
8900 State Line Road, Suite 455
Leawood, KS 66206
ph: 877-521-7769
© 2014 Keyhole Software, LLC. All rights reserved.