1 bug in 5000 lines and it's all thanks to...


TypeScript has to be one of the best new technologies that I am using this new year. After being offline for 7 days with my old Linux Laptop and just the latest Chrome browser, gEdit and the TypeScript compiler, I wrote over 5000 lines of code, testing it in just that one browser. With TypeScript picking up all my silly syntax errors and Chrome finishing off all the function/programmatic errors, the JavaScript that TypeScript helped me produce was next to flawless. I got home, tested it in all the major browsers (and some minor ones) and all I got, was one error in IE8 - even that barely counted as an error…

To clarify, the error I got in IE8 was simply the indexOf function not existing which, in a sense, is fair enough because IE8 is pre a lot of new features. (Though users who insist on not upgrading are more than a little irritating!) TypeScript and the TypeScript compiler really do make development faster, easier, much more robust and much easier to maintain.  Here’s just a few of the bets things is does: (I apologise now if this gets too close to a sales pitch for TypeScript, but it really has been that great to use!)

Static Typing

This has to be TypeScript’s most powerful tool - if it weren’t, what would be the point? I won’t discuss how to use it etc. since the TypeScript site does a good job of that but I will say that it works. Beautifully. Sure, when compared to properly typed languages such as C# it’s not quite as smooth and one or two of the jQuery definitions aren’t correct but it is smooth, easy and intuitive. There are other alternatives to TypeScript such as ones from Google, but as far as I can tell, you need to add definition comments  to everything. A messy and inconvenient solution. For every one line of code, I don’t want to have to write another that says what it was. TypeScript’s type definitions are inline using angle braces - a nice, simple solution that doesn’t impede my development at all. So a quick tip/trick then:

Got a variable that TypeScript says is of one type, but you know that it isn’t? E.g. a jQueryEventObject but you know really it is a MouseEvent? Well, there’s a nice easy hack to solve this but still keep TypeScript’s powerful type checking:

var event = <JQueryEventObject>{ };
var mouseEvent = <MouseEvent><any>event;

That simple cast to an any and then to the type you wanted solves the compiler issues and keeps TypeScript’s powerful static type checking later on in your code. Most of the time you probably won’t need this though - the provided function and type definitions are pretty accurate. I’ve only had slight issues with jQuery and had to extend the basic jQuery UI definitions file to include most of the basic of the UI widgets. My jQuery UI definitions file is downloadable for anyone to use, just click here (Note: File will be updated every so often - I will try and blog when I do so please follow me for updates).

Classes and Interfaces

JavaScript is a pain when it comes to developing large projects where you’ve got lots of UI controls and really you’d like a class for each with a common interface to handle them. To do this in JavaScript would be a nightmare to write manually, which is largely what the world has been stuck with. However, with TypeScript, life just became a whooollle lot simpler! Modules (namespaces), classes, interfaces, extension (inheritance) and implementation (implementing an interface) work just like Java as per standards but when you combine that with VS2012 intellisense and the TypeScript compiler, you get neat, efficient JavaScript that just works. And not just in IE, in any browser.

Declarations and Inferred Types

Okay so you might think I’m just listing TypeScript’s main selling points and perhaps I am but it’s only because it works - superbly. Declaration files allow you to take away that nasty native JavaScript from with your ts files and just declare what else will be included in your final HTML pages. And if you can’t be bothered to declare types for everything, the TypeScript compiler will infer the types based on first assignment - it will even infer types for native JavaScript code to help protect you! (or at least that’s what it seems to be doing :) )

Overall Review

I’m sold on TypeScript. If I were in a big company now, this would be a must on the upgrades list. Microsoft have done a fantastic job with the compiler - it produces reasonably efficient, neat JavaScript which sticks to standards so well, that if it works in one browser, you can be certain it’ll work in all the major browsers (Firefox, Opera, Safari, Chrome, IE 8-10 and of course every Android or iPhone browser I have gotten my hands on). Not only that but when it comes to debugging it, the unminifed files are so perfectly laid out (retaining much of the layout of the original TypeScript), that I’ve had no issues with getting lost in the mountains of code that go into a complex UI.

A small project

A small example of just one part of a project that I am working on is shown below:

An HTML5 (SVG) gradient picker written using TypeScript

At the top of the image you can see the gradient picker bar with the colour stops hanging below. The rest of the page is a large-scale, change-as-you-edit preview of the gradient that fills the whole page. This has compatibility with all the latest major browsers and also IE9 and mobile devices. Using SVG allows for the best compatibility while also using the least JavaScript processing time and is probably the easiest way to create linear and radial gradients that work across the web. Sadly, I can’t put the code up for the world to use but I can say that TypeScript made programming the whole thing much, much easier. I was able to extend (inherit) from an Event Manager class that I created a month ago to handle creating and firing custom onChange events etc. and easily use this jQuery ColorPicker plugin by adding to the jQuery declarations file. Even better, I am now able to use the gradient picker just like I would a UI control in C#. Just add a reference to the ts file, then create an instance of the control with its container div id! Very similar to jQuery, but using my own internal standard and written in TypeScript. If at any point I need to add to this, I can easily just inherit from my original code and then extend it as much as I like. Something that always feels a bit awkward in jQuery really…you don’t get proper extension really.

Converting to TypeScript

While converting my current JavaScript projects to TypeScript was a fairly laborious and somewhat slow process, I was able to dramatically improve the maintainability of the code. Since re-writing in TypeScript meant re-writing a lot of the code, I decided to do a full re-write from the ground up.  I should point at now that I didn’t have to re-write everything. TypeScript will allow you to put plain JavaScript in ts files and compile it - you just don’t get as many of the benefits of TypeScript.

Re-writing meant I could build in future-proofing, update from XML to JSON data format, improve stability and best of all - readability! If there is anything web developers hate JavaScript most for, it has to be that it is notoriously difficult to read. By the time you’ve finished adding in code to fix browser quirks and used all the little tricks you know to improve running speed, your JS code just looks messy. Even the TypeScript compiled JS code isn’t that nice to read. I think the best I’ve seen is jQuery but they do an extraordinary job of sticking to a neat layout - something a lot of developers just don’t do. (Not that I’m any better a lot of the time). But TypeScript has many of the same code formatting features as C#, which means your code looks good. I like the Visual Studio way of laying code out, and I love that it will now do it for TypeScript. Can it get any better? Well it certainly does. VS2012 will even allow you to collapse code blocks, comments and all the usual things you’d expect from a sane language. Unlike old versions of VS which didn’t really support JS or CSS, VS2012 does code collapse, decent syntax highlighting - the full works - for HTML, CSS, JS, TypeScript - you name it!  And with Web Essentials, CSS is even simpler too - auto add browser specific modifiers etc. - that’s a different discussion though. Ultimately, TypeScript and VS2012 are the reason I  can now open up my code and jump straight to where I want to be and read the code easily.

Conversion to TypeScript also allowed me to use proper inheritance. Duplicate copies of code is always bad. It’s even worse when you know you have duplicate copies. It becomes horrendous when you have to regularly make changes to the bit of code that you know is duplicated! I had this very same problem in my project. One bit of code, used in two places. In one place, it had it’s own “class” per se and worked fine. In the other, it was included within an extension class. Except that they were independent of each other. It wasn’t really an extension class, more of a duplication and addition. The JS was so complex, I found it impossible to get inheritance working let alone have just one copy of the code. From a maintenance point of view, this was awful. However, using TypeScript and its powerful module, class and interface capability, I was able to write just one class and then extend for my other class. One piece of code, in one place and any changes get applied in both places automatically - #wonderful.

Any projects anyone?

If you’ve got a project that you’re doing in TypeScript or you’d like a little help to get you started, please contact me! I’d love to hear about what others are doing and am always happy to help. Just visit my Contact page for my email address.

Have fun and happy coding!

(Please like/tweet if you liked this article or found it interesting/helpful!)