Wednesday, March 28, 2018

ECMAScript/Typescript gotcha: Map has to be used with set/get not like a Dictionary in .NET

In ECMAScript 6 there is a Map class that looks and feels like a .NET Dictionary. As an extension of JavaScript, TypeScript code like this is totally valid:
let map:Map<number,string> = new Map<number,string>();
map[1]="Category One";
let name:string = map[1]; //name is now "Category One"

However, the code above is wrong. What this does is create a string property named "1" on the map object with a value "Category One". Its "size" is 0. The correct code would be like this:
let map:Map<number,string> = new Map<number,string>();
map.set(1,"Category One");
let name:string = map.get(1); //name is now "Category One", map.size is 1

Similar code for ECMAScript 6, you can just declare the map as let map = new Map();

Just in case you wonder why utilize this hard to use type instead of a normal object, it's a user choice. Most of the pros involve the type of the key (object keys can only be strings or symbols) and ease of counting and iterating, but these issues can be solved trivially in code, if ever needed.

0 comments: