Introducing TypeScript — JavaScript on Steroids

Contributing Editor

Unless you’ve been hiding under a bush all week, you’ve no doubt encountered TypeScript; Microsoft’s new language for application-scale JavaScript development. There’s plenty of mis-information flying around, so I thought I’d join in…

First, TypeScript is not a replacement for JavaScript. TypeScript is to JavaScript as C++ is to C. It’s an extension of the language rather than a new syntax in its own right.

TypeScript is compiled (“pre-processed” or “transcompiled” would be a better description) into native JavaScript code. It’s a similar concept to CoffeeScript except TypeScript is far closer to JavaScript’s existing syntax; JavaScript++ if you like.

TypeScript Features

TypeScript offers static typing; you can define the data type of variables. The syntax is slightly unusual for those coming from C-inspired languages in that the type is specified after the variable, e.g.


function Hello(name: string) {
	return "Hello " + name;
}

Many developers will be overjoyed to find class declarations and inheritance, e.g.


// base class
class Language {
    private hasClasses: boolean;

	constructor(hasClasses: boolean) {
        this.hasClasses = hasClasses;
    }

    ClassSupported() {
		return (this.hasClasses ? "yes" : "no");
    }
}

// JavaScript language
class JavaScript extends Language {
    constructor(){
        super(false);
    }
}

// TypeScript language
class TypeScript extends Language {
    constructor(){
        super(true);
    }
}

var js = new JavaScript();
alert(js.ClassSupported()); // no

var ts = new TypeScript();
alert(ts.ClassSupported()); // yes

We also have interfaces:


interface Website {
	name: string;
	url: string;
}

function ShowSite(site Website) {
	return site.name + " at http://" + site.url + "/";
}

alert(ShowSite({ name: "SitePoint", url: "www.sitepoint.com" }));

Interestingly, an object doesn’t have to explicitly state it’s implementing an interface; it only need match the expected definition.

Finally, TypeScript implements modules, e.g.


module Say {
	export function Hello(text: string) {
        return "Hello " + text + "!";
    }
}
alert(Say.Hello("world"));

All code translates directly to JavaScript, e.g.


var Say;
(function (Say) {
    function Hello(text) {
        return "Hello " + text + "!";
    }
    Say.Hello = Hello;
})(Say || (Say = {}));

alert(Say.Hello("world"));

Microsoft has provided a great online playground to help you evaluate the syntax: www.typescriptlang.org/Playground/

I Like TypeScript Because…

Let’s look at the good stuff.

Developers new to JavaScript often struggle with the concept of prototypal inheritance. It’s a different mindset to classical inheritance concepts used in languages such as C# and Java. TypeScript offers reassuring comfort.

Sensibly, TypeScript uses the proposed ECMAScript Harmony class syntax. When that becomes widely available (don’t hold your breath), the TypeScript compiler won’t need to convert classes and your code will still run.

Static typing permits better IDE features such as auto-completion, refactoring and debugging. A plugin has been released for Visual Studio, Sublime Text, Vim and Emacs with more on the way. In other words, it should be easier to develop complex JavaScript applications.

TypeScript can be used on the client or server in Node.js. It’s a superset of JavaScript and compiles to raw, non-obfuscated code. Unlike Google’s Dart language, TypeScript doesn’t attempt to replace JavaScript entirely, require other browser vendors to add features or need chunky runtime libraries when it’s transcompiled. It has a far better chance of success.

The language has been designed by Anders Hejlsberg who brought us the excellent C#. TypeScript is open source and provided under the Apache 2.0 license at typescript.codeplex.com.

Finally, the TypeScript compiler is written in TypeScript. That’s brain-achingly cool.

But…

I suspect TypeScript will be adopted by developers using Microsoft .NET and Visual Studio. While it’s undoubtedly useful to others, there are sectors of the web development community who wouldn’t dream of touching a Microsoft product. Make up your own mind — there will always be “Microsoft! ARGH!! Noooo!!!” comments.

Microsoft created TypeScript because JavaScript remains the most misunderstood programming language ever devised. Opinion has improved in recent years, but you’ll still see comments stating JavaScript is a failure and shouldn’t be used by ‘proper’ developers. Few provide reasoned arguments other than their own snobbery or misunderstanding of the language.

I love JavaScript. It’s flexible, powerful and offers features which are being adopted by other languages. I can understand the rationale behind TypeScript and think it’s been implemented well, but I’m unlikely to use it when I’m more than happy writing native JavaScript code which is more efficient (or should be).

But if you’re not a gushing JavaScript fan-boy like me, TypeScript offers a compelling alternative.

For more information about TypeScript, head over to typescriptlang.org.

And — before you ask — Microsoft didn’t sponsor this article or ask me to write it.

Free book: Jump Start HTML5 Basics

Grab a free copy of one our latest ebooks! Packed with hints and tips on HTML5's most powerful new features.

  • emrah

    Microsoft, it is not a good move. Good move would be supporting dart lang.

    • Yoyo

      Dart is not Javascript. TypeScript IS Javascript.

      Dart is another move from Google to control the web. Nobody should accept to replace javascript with this corporation-controlled language, except Google fanboys.

    • http://www.optimalworks.net/ Craig Buckler

      Also, Dart is a closed technology. Microsoft couldn’t easily support it without licensing Google code or creating their own “DScript” implementation!

  • Matt Wistrand

    Correct me if I’m wrong, but this strikes me as the equivalent of a native JavaScript library (for example, if jQuery or MooTools were suddenly built natively into browsers and compiled into vanilla JavaScript). It actually seems like a pretty cool idea to me, but…
    1) Would it really be any faster than using any other library? The code still compiles to JS, meaning it needs to be interpreted by the same engine.
    2) If one of the motivations behind TypeScript is to convince developers that JavaScript is in fact a good language, it seems odd that one of the ways in which is does so is by trying to hide its prototypal nature behind a class structure.

    • http://www.optimalworks.net/ Craig Buckler

      That’s not correct. jQuery and MooTools are libraries written in JavaScript for JavaScript programs. They are not languages — simply a set of functions and objects.

      TypeScript extends JavaScript. You (can) use a different syntax which must be converted to JavaScript before it will run. You can still call jQuery or MooTools functions from TypeScript.

      It’s not about speed. TypeScript won’t run any faster than native JavaScript because it is native JavaScript. That said, the compilation process will generally be more inefficient than a program written in JavaScript from the start.

      I don’t think TypeScript is about convincing developers whether JavaScript is good or bad. TypeScript is simply another option which has a level of familiarity for those from C++, C# or Java backgrounds.

      • http://jonathanmarvens.com Jonathan Barronville

        - “That said, the compilation process will generally be more inefficient than a program written in JavaScript from the start.”

        I disagree. TypeScript generates JavaScript using best practices, the way that JavaScript developers should be writing JavaScript, therefore it’s actually as efficient as it should be. I’m building this large-scale JavaScript application. I’m currently converting my code to TypeScript, and honestly, I’m just now seeing all the mistakes I was making (or I should say “all the bad code” I was writing) with vanilla JavaScript. Even using something like “strict mode” in JavaScript, it still allows you to do things that I find horrible and consider non-sense coming from a C background. So I would not say that TypeScript is creates less-efficient code. Instead, I would say that TypeScript code might be less-efficient then the code one might write in vanilla JavaScript, because it’s doing things the right ways, which always takes more work then one thinks.

      • Weekoo

        I have a largish Javascript application which has been a nightmare to extend due to lack of proper classes in Javascript. During these two weeks I have added some functionality using TypeSript. I cannot but wonder at the quality of the Javascript code the compiler generates. It i clean, readable, even editable. Frankly, I could not make it any more efficient by editing it from scratch.

        It may well be true that in some cases the nested “function-objects” will generate some overhead but that is small problem compared to the problems caused by hand-optimized spaghetti code. Moreover, we have the same structure in jQuery, for instance and nobody has been complaining.

        I am convinced enough to start converting several JS applications to Typescript. I simply cannot think of any gotchas there might be. Should TypeScript die one day I still have the compiled, readable and editable Javascript code to continue work on.

        I considered using Dart but had great problems in having proper integration with my exisiting and external Javascript libraries and quickly rejected the idea.

      • http://www.optimalworks.net/ Craig Buckler

        @Jonathan. I’m not convinced TypeScript creates JavaScript in a way it should be written. JavaScript doesn’t (currently) support classes: you either embrace prototypal inheritance or code around it like TypeScript does.

        Of course you can do horrible things in JavaScript, but you can in any language — classes or not. It’s certainly possible to write elegant JavaScript applications. In my experience, the most convoluted JavaScript is written by those attempting to stamp pseudo-class structures on their code without considering alternative design patterns.

        However, I agree with Weekoo that TypeScript will help you think in a classical OOP way. If you’re used to C++, Java or C#, the transition will be far easier and outweigh any potential inefficiencies.

  • https://www.facebook.com/DotNet2Share Johnny

    Great article!

  • cc young

    Because Microsoft has worked very hard to obtain its ill reputation – remember Embrace, Extend, Extinguish – leaving one to have no choice but to be very careful in evaluating anything they produce. That said, TypeScript seems to be pulling in some of Dart’s typing and adding classical classes – which you call “reassuring comfort” and I would call “frankly boring”. Is the effort here to offer yet another syntactic sugar (eg Coffee) on top of javascript – one of the few languages that actually gets cooler the more you use it – or yet another sideways attack, this time against Dart – which has many cool subtle features – in the same manner in which Java was attacked? Why didn’t they just offer to work with Google – rename Dart to TypeDart – and make a layered offering that everybody could buy into? The problem is that it’s Microsoft, and I feel like Native Americans accepting free blankets from the settlers – instead of smallpox have a bunch of patents spread across my code.

    • Yoyo

      ” Because Microsoft has worked very hard to obtain its ill reputation – remember Embrace, Extend, Extinguish ”
      The same attitude that Google has adopted lately. I expect to see the same treatment for them from the Microsoft critics.

  • Patrick

    Whenever I see an article by Craig Buckler talking about how awesome some new web technology is, I get pessimistic because it’s probably going to be something borderline unusable given browser compatibility (or lack thereof). Luckily that isn’t the case today – this is a great development.

    TypeScript seems like a solid concept that has sensibly taken the needs of developers into account and is usable on current platforms. It addresses some of the shortcomings of JavaScript (and CoffeeScript) and I can see it becoming an industry standard in the next few years, much as CSS pre-processors have in the last few years. I’m a little surprised to see this kind of open-source innovation from Microsoft, but I’m happy someone has stepped up to deliver the kind of practical improvements that web developers can really benefit from. If they keep this up, Microsoft might actually be able to repair their horrible reputation in the web development industry.

  • Robbo

    I hate JavaScript! I’m going to be trying out dart lang a lot when I have time. And I’m not one of the people who don’t understand it. I see how powerful it is and know how to use it, doesn’t mean I have to like it. I work every day on PHP as well and I don’t exactly like it.

  • http://liveditor.com/ Edwin Yip

    I really like TypeScript (static typing, more readable class declaration, etc). I’m now investigating the possibility of supporting it in LIVEditor (live html, css and JS code editor at http://liveditor.com). Implementing code completion and live syntax hints are the key.

  • pete w

    I’ve written production code in silverlight AND coffeescript in the past 2 years.

    Frankly I feel a little burnt by both of these technologies. At the time I was solidly convinced this was the “future of the web”. Forgive me if I sit this one out and stick to the vanilla technologies until I see it gaining some widespread traction.

  • niutech

    You don’t need to use M$ products, like VS, to compile TypeScript into JavaScript. You can do it automatically and in-browser. Just use a small script called TypeScript Compile: https://github.com/niutech/typescript-compile

  • Jan

    “TypeScript is far closer to JavaScript’s existing syntax; JavaScript++ if you like.”

    Actually, there is already a JavaScript++ project, which is also a superset of JavaScript – http://jspp.javascript.am. Why isn’t JavaScript++ hyped up as much as its younger cousin TypeScript?

  • http://javascriptphp.com Yitz Meirovich

    We just debated this in the office and realized that while it may be nice to compile to JavaScript code, what happens when you start debugging in Chrome developer. You’ll hit an exception in the compiled JavaScript and will have no direct reference to the Typescript source. It can lead to debugging hell! What if the Typescript compiler outputs minified, optimized JS? It will look like the jQuery minified code looks. Try debugging that.

    If this runs the same way Microsoft currently allows you to debug with Visual Studio, then VS will attach to the browser event and will draw you back into the Typescript interface for debugging. I personally prefer Chrome Developer / Firebug to VS’s interface. Any other open source compiler will output JS that has no connection to the original source code and you’re on your own for debugging.

    While being open source in nature it really will be best for those with VS. Thus, a way for Microsoft to sell more licenses and still prove its relevancy.

    UPDATE: Just found a reference to Source Maps for Typescript that allows you to debug your Typescript in Chrome Canary. http://www.aaron-powell.com/web/typescript-source-maps While this looks promising there is overhead to configuring and running the outputted source map files. Certainly not a “plug-n-play” scenario. I’m sure it’s all been worked out for VS, however. So, again another reason to buy a license.

    My conclusion is that this is so new, and MS has such a history of starts and stops that it’s too soon to tell if this will amount to anything. Sounds good but so did so many other MS products. MS has never been known for coming out with exceptional products. I’ll stick with my plain ‘ol JavaScript and get by fabulously.

  • reichard

    You dont really know what lanuages and typing is about, do you?

    What you really have to compare is 2 things – intrusiveness and compatibility with already exisiting code base.
    In light of this you have to highlght benefits and minuses. While your points are taking from vanilla documentations and lack understading ofr problem domain.

    Then you really should show the issues abd benefits type system brings into DYNAMIC nature of javascript and into existing code.
    Such as dynamic dispatch, structural typing and pattern matching. Then you need to reflect the differences of it to Interfaces.

    Rings a bell?