Skip to content
Advertisement

map.get is not a function while retrieving a value from a map in typescript

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

Advertisement

Answer

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" ],
])
User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement