最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - map.get is not a function while retrieving a value from a map in typescript - Stack Overflow

programmeradmin0浏览0评论

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
  • 3 THat's not correct JSON. You want this, I guess, let map: Record<string, string> = { key1: "hello world 1", key2: "hello world 2" }; – Nishant Commented Feb 4, 2021 at 17:45
  • what is Record ? – Starbucks Admin Commented Feb 4, 2021 at 17:46
  • A utility type typescriptlang.org/docs/handbook/… – Nishant Commented Feb 4, 2021 at 17:47
  • i am still getting the same error – Starbucks Admin Commented Feb 4, 2021 at 17:50
  • alert( JSON.stringify(Object.keys(map))); – Nishant Commented Feb 4, 2021 at 17:52
Add a comment  | 

2 Answers 2

Reset to default 9

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

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"))  );
发布评论

评论列表(0)

  1. 暂无评论