LeverLabs

TypeScript, an Experience Report

written by Onne Gorter on 2015/11/02

My previous project was a game written in typescript. At first I was just prototyping some ideas in javascript. But then a game appeared and I needed to do some refactoring. Already bored with Item.prototype.update = function ... and needing some help while moving stuff about, I switched to typescript.

That allowed me to write in ES6 and sprinkle some types annotations here and there to get the most out of typescript.

Immediate Drawbacks

My write/test cycle went from zero to about 5 seconds. Somewhat annoying.

It also removes and changes lines as it outputs javascript. Not just stripping the types and translating the ES6/7 sugar. I wish it wouldn't do that, any browser errors have the wrong lines. And so do the debugger and profiler. It does support generating source maps though.

Also this repetition gets boring quickly:
class Something {
    field: number
    constructor(field: number) {
        this.field = field
    }
}
And if you leave off any of the type annotations (: number) typescript cannot help you anymore.

Edit: Wish I had noticed this sooner, typescript comes out ahead by actually reducing repetition:

class Something {
    constructor(public field: number) {
    }
}

Thanks to reddit user mrpatiwi.

Advantages

It did catch many typos, like this.prop that should have been this.sub.prop. Those are especially nasty in javascript because they become undefined and turn into NaN when doing math. Meaning that the code runs without warnings, but does not actually work either.

It also helps your editor doing autocomplete. I used Visual Studio Code. I also had it hook up to vim for a while.

That deeper understanding of typescript allowed me to refactor stuff knowing I didn't break any or missed any cases.

Where you want, you can get all the advantages of a statically checked language. But you don't have to pay that price immediately or everywhere. And writing types down serves as good documentation.

But was it Worth it?

I started my next project in ES6 (and "use strict", as I always do). No typescript.

A zero seconds write/test cycle is much better. Most typo's typescript catches are immediate runtime errors anyway. And I use asserts here and there for when I know any mistake will take me long to track down.

function assert(c, desc) {
    if (c) return
    var e = new Error(desc? "Assertion Failed: "+ desc : "Assertion Failed")
    e.message += e.stack.split("\n")[2]
    throw e
}

Plus these are games. Before any code can be documented it has changed already.

But I did miss some aspects of typescript. So I looked into flow. More on that in a next blog.

Submit to Hacker News