Friday, May 22, 2015

Tuples and destructuring in TypeScript

I have been interested in TypeScript for a while, AngularJS 2 has put it on the developer's map now.

A feature that I look for in any of the new languages now is tuples and destructuring. It makes it easier to return multiple values from a function and assign it to different variables and not an array. TypeScript has it too, example:

TypeScript code:

function returnTuple(a: string, b: string) {
return [b, a];
}
var n = 'World!', m = 'Hello';
var p: string, q: string;
[p, q] = returnTuple(n, m);
alert("result: " + p + " " + q);

Generated Javascript code:

function returnTuple(a, b) {
    return [b, a];
}
var n = 'World!', m = 'Hello';
var p, q;
_a = returnTuple(n, m), p = _a[0], q = _a[1];
alert("result: " + p + " " + q);
var _a;

A run shows an alert with "Hello World!"
A bit like the Go playground, Typescript has one too: http://www.typescriptlang.org/Playground so you can test and play with the code there!