Home > OS >  How to create a Map of different type of value in typescript
How to create a Map of different type of value in typescript

Time:11-22

I have started learning Typescript and I was trying to create a map with different type of values, but it's not working. I tried directly giving string and number as an options while defining the Map but it's throwing error that we are unable to map number to string

const testMap: Map<string,string|number> = new Map([["a", "test1"],["b","test2"],["c",1]]);

Please suggest.

Playground

CodePudding user response:

Typescript is not able to infer value type properly in this case, but you can specify generic type parameters explicitly when calling Map's constructor:

const testMap = new Map<string, string | number>([["a", "test1"], ["b", "test2"], ["c", 1]]);

Playground

  • Related