What is TypeScript?

This week Microsoft released a preview of a language called TypeScript that adds additional features to good old JavaScript (a language I’m sure some of you don’t like that much). TypeScript auguments JavaScript with additional features such as strong typing, classes & interfaces and lambda syntax. These features are aimed at facilitating development and also make possible some interesting IDE features such as intelli-sense and compile time checks.

I was sceptical at first at the idea of TypeScript with my initial reaction being –do we really need such a language when we have the much more mature languages such as coffeescript etc for adding additional functionality?

I guess I am not entirely convinced by the concept of a language that sits on top of another to provide minor enhancements (ignoring the fact many languages could be considered to work this way) such as CoffeeScript for the following reasons:

  • Maintainability – other people have to maintain the code and in the example of CoffeeScript it’s hard enough to find decent JavaScript devs in the Microsoft space let alone one that knows CoffeeScript as well
  • CoffeeScript is another language to learn with quite different syntax and I am unconvinced the benefits are worth the investment from learning it – my understanding is CoffeeScript enables a nicer, terser syntax and prevents you falling into a few traps (learn JS properly I always thought) big woo!
  • Debugging is going to be a pain in the butt as a coffee script file looks pretty different from a JavaScript file

So does TypeScript suffer from some of these issues?

Well the first thing you notice about TypeScript is that its immediately recognizable as JavaScript which isn’t so surprising given that a valid JavaScript file is also a valid TypeScript file.

TypeScript files are compiled into plain old JavaScript so they can be run on anything that JavaScript can. There is also a Node.js package for TypeScript if you’re a hipster – like Aaron Powell who I dreamt a few nights ago was teaching me the electo synth but I digress..

To get the most of TypeScript you want to install the Visual Studio extension which gives you syntax checking, intellisense etc. This allows you to create TypeScript (.ts files) and when you build have TypeScript check for various issues. This will also install the typescript command line compiler tsc

ts_commandline

Note how TSC has some additional options including version of ECMA script to compile to and options to export modules etc.

TypeScript is open source so there is nothing stopping anyone else from developing add ons for other IDEs and apparently there is already basic text editor support for editors such as Sublime & EMACs. The TypeScript compiler source is also available which is interesting to see how this kind of thing works.

So let’s look at some of the features TypeScript gives you.

Typing

It’s probably little surprise that a language called TypeScript includes some stuff to do with Typing. Typing I guess is a little weird in JavaScript and something that can be a bit tricky to understand & predict in its more esoteric cases.

Types in TypeScript can be number, bool, string or any (anything else). Apparently there is also a void type for indicating a function doesn’t return a value but I don’t know much more at this stage.

TypeScript allows you to add information about types so that the compiler can use to spot mistakes and give you intellisense e.g.:

So how do you indicate a variables type? A simple example is shown below:

function doSomething(x: string, y: number) {

}

The type attributes allow the compiler to catch errors such as

doSomething(“hello”, “will fail as im a string”);

It will also catch errors where you don’t supply enough arguments to a function e.g.

doSomething(“blah”);

If you want to declare an argument as optional you can do so by appending a question mark to the variable name:

function doSomething(x: string, y?: number) {}

Interfaces

TypeScript adds interfaces which you can reference which can assist with compile time checks e.g the function below expects an object conforming to ICar:

interface ICar {

type: string;

drive: string;

}

function CreateCar(car : ICar) {}

We can use these interfaces to indicate the type of parameters we are expecting on our methods. This enables Visual Studio to give us more information about the class and also catch any invalid function calls.

Classes

JavaScript has always enabled you to emulate traditional OOP constructs such as classes although they can look a little esoteric and there are some traps to catch you out. TypeScript gives you a nice syntax for declaring a class and its constructor:

class Person {

public name: string;

constructor(name: string) {

this.name = name;

}

whatsMyName(): string {

return this.name;

}

}

var p1=new Person(‘alex’)

This compiles to:

var Person = (function () {

function Person(name) {

this.name = name;

}

Person.prototype.whatsMyName = function () {

return this.name;

};

return Person;

})();

var p1 = new Person(‘alex’);

Which is probably pretty similar to what you would have written in js anyway..

You can also mark properties as private which seems to hide them from intellisense but doesn’t actually seem to change the generated JS as far as I can see at present.

Static modifier

You can declare static methods like so:

class person {

static DoSomething(){

}

}

person.DoSomething();

Inheritence:

TypeScript has a great syntax for inheritance which was always a bit gnarly in pure JavaScript and contained a number of traps if you didn’t call functions in the way they were expecting:

class Person {

public _firstName: string;

constructor(public firstName: string) {

this._firstName = firstName;

}

}

class Employee extends Person {

public _company: string;

constructor(public firstName: string, public company:string) {

super(firstName);

this._company=company;

}

}

var alex=new Employee(“alex”, “kiandra”)

Generates:

var __extends = this.__extends || function (d, b) {

function __() { this.constructor = d; }

__.prototype = b.prototype;

d.prototype = new __();

}

var Person = (function () {

function Person(firstName) {

this.firstName = firstName;

this._firstName = firstName;

}

return Person;

})();

var Employee = (function (_super) {

__extends(Employee, _super);

function Employee(firstName, company) {

_super.call(this, firstName);

this.firstName = firstName;

this.company = company;

this._company = company;

}

return Employee;

})(Person);

var alex = new Employee(“alex”, “kiandra”);

Eek! you probably didn’t want to write that stuff yourself!

You can even downcast types and have them checked for type safety:

var alexAsPerson = <Person> alex;

Lambda syntax

As a C# dev I love the lambda syntax that TypeScript gives me (this syntax is also a proposal in ECMA6)

var calculator={

addTowNumbers: (x,y) => {return x+y}

}

This compiles to:

var calculator = {

addTowNumbers: function (x, y) {

return x + y;

}

};

Nice!

Modules

One of the harder aspects of JavaScript is keeping everything organized and reusable.  TypeScript gives you a nice syntax to declare modules and exports to keep your code organized:

module Utilities {

export class AddTwoNumbers {

private _x:number;

private _y:number;

constructor (x: number, y: number) {

this._x=x;

this._y=y;

}

add():number {

return this._x + this._y;

}

}

}

var calc = new Utilities.AddTwoNumbers(1,2);

calc.add();

So what next?  

Well there is a little documentation & tutorial on the main site at http://www.typescriptlang.org and a test page that allows you to enter TypeScript and see the JavaScript it compiles to. But for a more detailed look head over to Channel 9 at http://channel9.msdn.com/posts/Anders-Hejlsberg-Introducing-TypeScript, Anders discusses a number of features not on the mains site such as exporting functions and the interface files.

However to really get into TypeScript at the moment you are going to have to look at the source code as there isn’t too much doco around yet but im sure this will change 🙂

Conclusion

Things I like:

  • TypeScript was easy to pick-up and still felt like I was writing JavaScript
  • It still looks like JavaScript and would be easy to maintain
  • It offers additional intelli-sense and syntax checking
  • The generated script follows existing & proposed standards. Microsoft say they are keen to keep in line with these standards as they develop
  • The syntax for class generation is much nicer than writing it yourself
  • Everything is open source & you can even see how the compiler works – which is also written in TypeScript which hurts my head 🙂

Things I don’t like:

  • Not much actually

But…I guess I have never really been burned by JS’s typing system or lack of compile time checks so I do wonder how useful some of these features will be.

Having said that on one of my previous consultancy engagements the client complained of a dev making a syntax error and breaking all the JS on the site so maybe something like TypeScript could avoid these types of issues (or possibly a better code structure or deployment/testing process!). Having constructs such as interfaces & modules available I guess could be important in larger environments for large teams working together.

Anyway I suggest you give it a go – I liked what I saw so far & it will be interesting to see how this project develops.

Advertisements

2 thoughts on “What is TypeScript?

  1. Great informative article. I love the type checking in Typescript, but I have to say that, like others, automatically compiling the files when you want to debug your page in Visual Studio is a real problem. The add-ins, extensions and what not, don’t work for a lot of people. I ended up having to write an app to solve the compilation issues with TypeScript. If you’re having these issues, here’s a solution: http://onthefly.codeplex.com/

Comments are closed.