9

I am having a map with key and value as strings. However when trying to retrieve a value based on the key it is throwing error .

the following is my code snippet.

let map:Map<string, string> =  {  [ "key1": "hello world 1" ], ["key2": "hello world 2"] } ;
alert( JSON.stringify(map.get("key"))  );

the exception i got below is as follows.

VM133:4 Uncaught TypeError: map.get is not a function
    at eval (eval at exec (typescript.js:41), <anonymous>:4:26)
    at exec (typescript.js:41)
    at HTMLDocument.runScripts (typescript.js:41)

appreciate if you can tell me what am I doing wrong

thank you

Starbucks Admin
  • 585
  • 1
  • 8
  • 21

2 Answers2

7

A Map is not a primitive and needs to be called with the constructor (I think Typescript should have warned about this).

See the MDN documentation for Map

You're probably looking for this:

const map:Map<string, string> = new Map([
  [ "key1", "hello world 1" ], 
  [ "key2", "hello world 2" ],
])
Codebling
  • 10,764
  • 2
  • 38
  • 66
3

I think you should create a map like this in typescript, you're missing the constructor call. What you've right now is just an object literal that is also formatted in a wrong way.

let myMap = new Map([
        ["key1", "value1"],
        ["key2", "value2"]
    ]);
alert( JSON.stringify(map.get("key1"))  );
Mu-Majid
  • 851
  • 1
  • 9
  • 16
  • can i ask a quick question . How can i declare [ ["key1", "value1"], ["key2", "value2"] ] this as a typed variable . is let arr:[ [string,string] ] , is this correct ? – Starbucks Admin Feb 04 '21 at 18:46
  • hmmm, I think you'd have to define your Maps interfaces, like this, `interface myMap { // whatever your key and values }` – Mu-Majid Feb 04 '21 at 19:48
  • 1
    I have found this answer https://stackoverflow.com/questions/40976536/how-to-define-typescript-map-of-key-value-pair-where-key-is-a-number-and-value, you can check it and see if it serves your purposes – Mu-Majid Feb 04 '21 at 19:48