1

I want to create a Map() object that has a bunch of values. What is the best way to go about this? Right now I am just doing new Map<keyof Data, any>([...myArray]). I am going to making a few different of these maps so it would be nice to have a way to be able to pass the objects data in instead of having any as the values. Here is a very simple example.

type Data1 = {
    obj: {
        a: number,
        b: number
    },
    str: string
}

const data1 = new Map<keyof Data1, any>([
    ['str', 'value1'], 
    ['obj', {
        a: 1,
        b: 2
    }]
])

type Data2 = {
    obj: {
        one: number,
        two: number
    },
    bool: string
}

const data2 = new Map<keyof Data2, any>([
    ['bool', true], 
    ['obj', {
        one: 1,
        two: 2
    }]
])

Is `Map()' maybe not the best tool for this type of functionality? Should I maybe just use a regular javascript object for this type of data pattern?

user3331344
  • 728
  • 8
  • 23
  • Maps are homogenous by nature. If you want this kind of behavior, you have to extend `Map` and override the types. – kelsny Mar 16 '23 at 03:11
  • @vr.Should I maybe just use a regular object instead? I like the syntax of setting and getting so I figured I would try the `Map()` but maybe it is not the tool for the job. – user3331344 Mar 16 '23 at 03:16
  • See the [linked question/answer](https://stackoverflow.com/questions/54907009/typescript-how-can-i-make-entries-in-an-es6-map-based-on-an-object-key-value-ty) for more info. If you use the approach there you get [this](https://tsplay.dev/mZ1qeN), but plain objects are definitely more conventional for this purpose. – jcalz Mar 16 '23 at 03:31

0 Answers0