Reputation: 1549
In TypeScript I can delcare a map like this:
{[key:number]string}
As an example of a map whose keys are numbers and values string. But I can also do it like this:
Map<number, string>
Why do we have two ways to do the same and what is the difference among them?
Upvotes: 2
Views: 90
Reputation: 771
A Map
is a native JS object that holds pairs of keys and values. So you can do:
let myMap = new Map();
myMap.set('bla','blaa');
myMap.set('bla2','blaa2');
And that will create a map with those values.
Your other type, {[key:number]: string}
, types an object that has the keys of type number
and the values of type string
. The main difference between a map and a plain object is a map's key can be anything (it doesn't have to be a string, number or Symbol unlike object) and it is also better optimized. See the MDN documentation for a full list of differences.
Upvotes: 1