Patrick Desjardins Blog
Patrick Desjardins picture from a conference

TypeScript Hashmap Equivalence in JavaScript

Posted on: 2014-10-21

TypeScript is transformed into JavaScript and sometime you start some of your code into TypeScript and finish into JavaScript. This is a scenario that you can see when developing some code in TypeScript and at some point is integrated into some existing JavaScript code.

TypeScript allows to have hash map in which you define the type for your key and for the value that it will hold. Let's take the example of a hash map that has a string key and a string value.

var arr = { [path:string]:string; }; //Hashmap that has for key a string and for value a string 

If you need to use this variable in JavaScript and be sure that it will continue to work when coming back into some JavaScript generated by TypeScript you have to keep in mind that this is in fact a double array. If you want to define some values for this variable, you must define for each key a property that contains an array of value. For example imagine two keys with two values each like the example below.

var arr = {'k1':['p1','p2'],'k2':['2p1','2p2']} 

This is a working example that can be read back in TypeScript. It is also possible with JavaScript to get back all information by looping through all the keys and values even if the k1 and k2 of the previous example are properties.

for (var key in arr) { 
  var allValues = arr[key]; 
  for (var keyValue in allValues) { 
    console.log('Key ' + key + ' has value : ' + allValues[keyValue]); 
  } 
}