Quick and dirty look at TypeScript

January 29, 2015 by TypeScript  

Last year (2014) I had a quick glance at TypeScript for the first time, but I didn't pay too much real attention to it. I pretty much felt it was simply Microsoft's response to Google's dart language. At first glance this seems pretty obvious, they largely "do" the same thing, share a lot of similarities in syntax, both compile to JavaScript etc.

I also didn't like the whole idea of one high-level language compiling to another high-level language, it all feels very redundant.

Ideally we would rather want to add what we need to our high-level language (JavaScript in this case), instead of creating another language on the other side of the compiler. Its a lot more complicated than that though, especially seeing that nobody really seems to own JavaScript, every vendor is responsible for their own implementation of the language.

Putting all of this aside (deeper discussion for another day), I started playing with TypeScript the last few weeks and I am pleasantly surprised - I really like what I am seeing.

To put it bluntly, TypeScript is JavaScript (or strictly speaking a superset of it), but an updated/evolved version of JavaScript, you still get to write all the JavaScript you love (or hate) using the exact same language, while using all your existing JavaScript libraries!

Lets have a quick look at some of the things TypeScript brings to JavaScript (notice the C# influences).

Typed vs UnTyped 

JavaScript is an untyped language, which basically means we don't declare the types of our variables. In TypeScript however you can declare the types for your variables, thereby constraining that variable to whatever type you declared:

var isValid : boolean = false;
var firstname: string = "Christoff";
var myAge: number = 31;
var list: number[] = [1, 2, 3, 4, 5];


Alternatively the types will be inferred from the value assigned to it.

var myAge = 31; // Type number inferred


But this is where it gets interesting, this will constrain the variable in the same way a declaration would.

myAge = "1983/02/02"; // Error: Type string is not assignable to Type number


This is consistent to how implicit typing works in C# but different to the type "juggling" we see in JavaScript which is unconcerned about what we assign to our variables - like a dynamic variable in C#. If you need your variable to behave like a traditional JavaScript variable, you have to explicitly declare it as an Any type.

Union Types

I discovered the following syntax by accident while downloading the type definitions for jQuery via nuget, it wasn't part of the official TypeScript handbook at the time of writing this post - introduced in version 1.4.

var age: string | number;
age = 31;
age = "Thirty One";
age = true; // 'boolean' is not assignable to type 'string | number'.

Basically we're telling the compiler that our type can either be a string or a number, but restricted within those types.

Enum

In TypeScript (like C#) we can declare an enumeration, which is basically a set of named constants - no more magic numbers.

enum Colour {Red, Green, Blue};
enum Colour {Red = 1, Green = 2, Blue = 4};


Optional, Default and Rest Parameters

In JavaScript all function parameters are considered optional, in TypeScript however, you need to tell the compiler which parameters are optional, in the following snippet we add a question mark next to the optional parameter.

function search(text: string, results?: number) { }

To specify a default value for a parameter, we simply assign a value to it, like seen below:

function search(text: string, results = 10) { }

If you want the ability to provide a variable number of parameters, like with the params keyword in C#, you need to add an ellipsis (...) in front of the parameter, this is called a rest parameter. This is treated as an optional parameter, or rather optional list of parameters.

function search(text: string, ...types: number[]) { }

Classes

I am not going to go into too much details about classes in TypeScripting, but you can do all the usual stuff like inheriting from other classes and interfaces, use access modifiers (private/public/protected) to set the visibility of your members, have property accessors with getters and setters.

class House {
    private _address: string;
    constructor(address: string) {
        this._address = address;
    }
    get Address(): string {
        return this._address;
    }
    set Address(value: string) {
        this._address = value;
    }
    public knock() : boolean {
        return true;
    }
}

There is however one interesting and unusual thing I found in the official documentation and want to point out and that is parameter properties.

class House {
    constructor(public address: string) {
    }
}

Assigning an access modifier to a parameter in our constructor is shorthand for creating and initializing a class property.

Modules

Modules are essentially like namespaces, it allows us to group related classes, object, enums etc together into an unique little container. Note the use of the export keyword in the snippet below, this makes the "exported" items accessible to code outside the module - like an access modifier in C# would.

module Animals {
    export class Horse {
    }
    export module Pets {
        export class Dog {
        }
        export class Cat {
        }
    }
}

Interfaces

Interfaces allow us to define the structure (or contract) that classes, objects, types, hybrid types and functions must conform to, as well as allowing us to specify definitions for the raw JavaScript libraries we use inside our project(s).

I am not going to go into much more detail than that in this post, perhaps a topic for a near feature post, it is quite a topic on its own. It seems to be a bit more involved than what we are used to in languages like C#, Java, PHP and others.

It will be interesting to see how this new language will be received by the larger JavaScript community, especially seeing that in a sense JavaScript is like an intersecting point between dev communities, some like their coffee weak, some like it strong, most like it hot, some like it frozen.

Additional reading

Official TypeScript Homepage
DefinelyTyped repository


Leave a Comment