Starbucks Admin
Starbucks Admin

Reputation: 937

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

Upvotes: 13

Views: 34993

Answers (2)

Codebling
Codebling

Reputation: 11382

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" ],
])

Upvotes: 9

Mu-Majid
Mu-Majid

Reputation: 845

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"))  );

Upvotes: 3

Related Questions