5

If I want to have string:object dictionary with type checking in TypeScript, there are two ways doing that which I'm aware of:

const m = new Map<string, MyObject>();
m.set("a", new MyObject("a"));
m.set("b", new MyObject("b"));

and

const m : {[index: string]: MyObject} = {};
m["a"] = new MyObject("a");
m["b"] = new MyObject("b");

What are advantages and disadvantages of each of them? If there another way to declare and work with string:MyObject dictionary?

lebed2045
  • 428
  • 2
  • 7
  • 15

1 Answers1

2

As has been detailed in this answer (up vote this before mine!), an object with typed key and value (sometimes called a hashmap) was commonly used in Typescript before it had support for Map:

const m : {[index: string]: MyObject} = {};

The problem with this approach is that keys can only be of type string or number, and it actually doesn't matter what you use as the key type, since numbers/strings are still accepted interchangeably (only the value is enforced).

Typescript now has native support for ES6 Map type, which doesn't have any of the disadvantages regarding the key mentioned above. As for advantages of the hashmap compared to the Map, I cant see any.

However if you did want to interact with the (now legacy) Map type via the index operator you could do so by wrapping it in a Proxy e.g.

const map = new Map<string, number>();
// Set the value of "a" using Map's set function
map.set("a", 123);

const handler = {
    get: (target: Map<string, number>, name: string) => { return target.get(name)},
    set: (target: Map<string, number>, name: string, value: number) => {target.set(name, value)}
};
const mapWrapper = new Proxy(map, handler);

// Now add "b" to the Map with the value of 321 via the Proxy wrapper
mapWrapper["b"] = 321;

You can see this example running here.

Ben Smith
  • 19,589
  • 6
  • 65
  • 93
  • is there any way to use Map via [] operator? – lebed2045 Apr 23 '19 at 19:00
  • 1
    @lebed2045 You could use Map via the [] operator by wrapping it in a JS Proxy. [Here's](https://jsfiddle.net/Fresh/5wmxpyt1/) an example I've written. I agree that it feels like the JavaScript Map should have native support for this operator. Let me know if you want me to add that to my answer (you could say that should be a separate question). – Ben Smith Apr 23 '19 at 22:43
  • yes, if you could add this to the answer, I think this would be valuable for other people. – lebed2045 May 16 '20 at 09:01
  • @lebed2045 Done! – Ben Smith May 16 '20 at 22:07