I've been watching the TypeScript project for a little over a year now, since the 1.0 release. The concept really interested me, but as is the case with many new language conventions, I wasn't sure whether or not it would catch on. However, the recent announcement that Typescript would be used to build AngularJS 2.0 gave me confidence that TypeScript was legit and here to stay. I decided it was time to start a little sample project (posted below) and explore.
While building the said project and preparing to write this post, I came across quite a few "Introduction to TypeScript" articles. This is not intended to be one of those articles. They have their place, to be sure, and I used a number of them to get started on my journey. However, I want to take a different angle - I want to pose back to you, and answer, the same questions that were in my head when I started watching the TypeScript project:
- Why should you use TypeScript in your next web or mobile project?
- What makes TypeScript sweet - meaning how will it make your job easier and your project better?
- Essentially, how does it put the sugar in your java[script]? (sorry, I had to)
Here's what I liked about TypeScript:
TypeScript is Excellent at Helping You Organize Your Code
TypeScript offers the ability to create modules that really help in this area:
- Modules work like namespaces in C#. They help to group like objects together, as well as avoid name collisions with other objects and over-saturation of the global namespace.
export keyword restricts access to code outside the module, clearly defining what's intended for public consumption and what isn't. Law of Demeter, anyone?
- Classes within a module can be split across multiple files for simplified maintenance, readability and reuse (more on that in a moment).
You may notice that I didn't split my code into separate files. I decided not to simply because I wanted to post a single Gist file for all of it. If it is part of a bigger project, I'd probably have a separate file for each class.
TypeScript Helps You Share & Reuse Your Code
This is the result of points #1 & #2. At the risk of stating the obvious, if you have high quality code that's well organized, it's easy to share or reuse it in multiple projects. For example, if you were to split up my code below so that each class was in a separate .ts file, it would be easy to maintain the classes as part of a common library, but also to select only the pieces you want for a specific application. Maybe you don't need to make API calls, but you need a
Timer or a
ResultLog? The structure and conventions of TypeScript make this easy.
* * * * *
Here's a link to my sample project - it's an API testing module modeled after a PowerShell script I wrote a few months back. The TypeScript module code is below; there's also a sample HTML page that shows how to execute it.