I am trying to map some Java code which uses Map's to Typescript code. My initial thought was to use Map's in Typescript but for the interface I was creating this did not work out. Instead I found Records which seemed to emulate Java's Map's perfectly.
My main question is when should I use Typescript's Maps over Records and when should I use Typescripts Records over Maps?
How do they work differently?
viewMappings: Record<string, String[]>;
viewMappings: Map<String, String[]>;
for example
I expect these to work in an interface with my State very similarly but they do not and am looking for documentation of the differences of the two.
We can regard maps as documenting places and archives catalogues as documenting accumulations of records. In principle, catalogues allow researchers to make sense of archival collections before, during and after interacting with them directly44; reading the map is part of the user journey.
TypeScript Records are a great way to ensure consistency when trying to implement more complex types of data. They enforce key values, and allow you to create custom interfaces for the values. The TypeScript Record type was implemented in TypeScript 2.1, and takes the form Record<K, T> .
In short, you should always use a Map when you need a key-value collection. A good indicator that you need a collection is when you add and remove values dynamically from the collection, and especially when you don't know those values beforehand (e.g. they're read from a database, input by the user, etc).
Record is defined as
type Record<K extends keyof any, T> = {
[P in K]: T;
}
While Map
is a native JS ES6 data structure. Record is merely a representative way of saying, "this object is going to be used a key, value map of a specific data type". It's a plain object created using {}
. The Map
object on the other hands has some unique characteristics described here and needs to be instantiated as new Map()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With