TypeScript musings

So I frequently use a JavaScript routine like this:

var vars = [], hash;    
var q = document.URL.split('?')[1];    
if(q != undefined){        
    q = q.split('&');        
    for(var i = 0; i < q.length; i++){            
        hash = q[i].split('=');            
        vars.push(hash[1]);            
        vars[hash[0]] = hash[1];        
    }
}

So let’s see what we can do with this in the world of TypeScript. Goals here:

  • Add some type safety declarations
  • Drop it in a module
  • Update it a little as this was a really old snippet in JavaScript land.

So starting with the hash map and creating a class in typescript:

class QParams {
    vars: { [field:string]:string; };  // A Typescript Hashmap
    qstr: string;

    constructor() {
        this.qstr = document.URL.split['?'][1];
        if (this.qstr != undefined) {
            // Here I wanted to pause because in the original javascript
            // q was overwritten from a string to an array of strings
        }        
    }
}

Now reorganized and add a few more bits for the extra array:

class QParams {
    paramhash: { [field: string]: string; };  // A Typescript Hashmap
    params: string[];
    qstr: string;

    constructor() {
        this.qstr = document.URL.split['?'][1];
        if (this.qstr != undefined) {
            this.params = this.qstr.split('&amp;');
            for (var i: number; i &lt; this.params.length; i++) {
                var pair = this.params[i].split('=');
                this.paramhash[pair[0]] = pair[1];
            }            
        }
    }
}

Then run this through the typescript compiler produces this javascript:

var QParams = (function () {
    function QParams() {
        this.qstr = document.URL.split['?'][1];
        if (this.qstr != undefined) {
            this.params = this.qstr.split('&amp;');
            for (var i; i &lt; this.params.length; i++) {
                var pair = this.params[i].split('=');
                this.paramhash[pair[0]] = pair[1];
            }
        }
    }
    return QParams;
})();
//# sourceMappingURL=qparams.js.map