Nov 15, 2013

Tinkering with TypeScript

I have been tinkering with TypeScript for a few months now, and wanted to briefly share something useful I just learned.

You may be familiar with the Math.floor('123') integer type-cast, which is useful for high-performance applications because it's generally much faster than e.g. parseInt('123'), and does essentially the same thing.

I wanted to do this in TypeScript, but I got an error:

var value = '123';
var int_value = Math.floor(<number> value); // FAILS

It won't let you type-cast a string to a number, which is sensible enough - however, it will let you cast an any to whatever you want, so this double typecast will do the trick:

var value = '123';
var int_value = Math.floor(<number> <any> value); // WORKS!

It looks a little odd, and it seemed dumb to me at first - but after thinking about it, I realized I like it - it's a double assertion, both for the compiler and for a programmer reading the source code: you're saying, "I know this is dangerous, but I know what I'm doing".

And since this is all happening at compile-time, the resulting code will be just as fast as the raw, no-guarantees, plain JavaScript version.

Passing a string to Math.floor() in JavaScript should raise questions, if the reader is observant enough to even notice that's what's happening - in TypeScript, you're required to explain and justify what you're doing, in this case with typecasts.

One of many reasons why I really like TypeScript.