Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Differences between and when to use Map vs Record

Tags:

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.

like image 249
Michael Smith Avatar asked May 31 '19 15:05

Michael Smith


People also ask

Is a map a record?

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.

When should I use TypeScript records?

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> .

Should I use map JS?

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


1 Answers

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()

like image 141
Avin Kavish Avatar answered Oct 21 '22 13:10

Avin Kavish