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.
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]]);