5

I create a map in typescript like this:

let typeMap = new Map();

And set a key: string value like this:

typeMap.set("key", "value");

I can successfully get value by doing this:

typeMap.get("key")

However, I want set multiple key value pairs to the map and setting each key value would be too much code. I tried doing this:

let typeMap = new Map<string, string>();
typeMap = {
   "key1": "value1",
   "key2": "value2"
   //etc
}

But I'm getting

Object literal may only specify known properties and "key1" does not exist in type 'Map

I also tried the following:

  type typeMap = {
    [key: string]: string
  }
  let typeMap = {
    "key1": "value1",
    "key2": "value2",
    "key3": "value3"
  }

If I try to get a static value like this:

typeMap["key1"]

It works. However, I have a variable that must be passed as key to get the value and when I try to do this:

typeMap[variable]

I'm getting:

Element implicitly has an 'any' type because expression of type 'string' can't be used to index type '{ "key1": string; "key2": string; "key3": string; }'.

No index signature with a parameter of type 'string' was found on type '{ "key1": string; "key2": string; "key3": string; }'

Bogdan
  • 379
  • 2
  • 5
  • 19
  • 1
    Does this answer your question? [How to convert a plain object into an ES6 Map?](https://stackoverflow.com/questions/36644438/how-to-convert-a-plain-object-into-an-es6-map) – Spatz Jan 16 '20 at 08:29

1 Answers1

6

You may be confused with Map and JavaScript objects. A simple javascript object such as {} is not the same thing as new Map(). You've defined the typeMap as a "map", and then you are trying to update it with an object. Either use Map and then use .get/.set or use an object with your the interface you want:

// Use type
const typeMap = new Map<string, string>();
typeMap.set('key1', 'value1');

// would print value1
console.log(typeMap.get('key1'));


// Or use an interface
interface IMap {
    [key: string]: string;
}
const objectMap: IMap = {};
objectMap.key1 = 'value1';

const key = 'key1';
// in both cases, prints value1
console.log(objectMap.key1);
console.log(objectMap(key));
Kousha
  • 32,871
  • 51
  • 172
  • 296