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
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
Share Improve this question edited Feb 4, 2021 at 17:45 Starbucks Admin asked Feb 4, 2021 at 17:42 Starbucks AdminStarbucks Admin 9372 gold badges13 silver badges30 bronze badges 5 |2 Answers
Reset to default 9A 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" ],
])
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")) );
let map: Record<string, string> = { key1: "hello world 1", key2: "hello world 2" };
– Nishant Commented Feb 4, 2021 at 17:45alert( JSON.stringify(Object.keys(map)));
– Nishant Commented Feb 4, 2021 at 17:52