Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create a Map of different type of value in typescript

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

like image 360
Sandeep Bisht Avatar asked Sep 13 '25 02:09

Sandeep Bisht


1 Answers

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

like image 165
Aleksey L. Avatar answered Sep 14 '25 23:09

Aleksey L.



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!