0

I have been trying to initialize a Map type from a JSON blob, when I have a defined type for the expected JSON response. For example, we have a t-shirt size type.

This is how the JSON blob looks like:

const blob = `{
    "name": "TShirtSize",
    "description": {
        "S": "Small",
        "M": "Medium",
        "L": "Large"
    }
}`

and this is a type I have created for the JSON blob.

export type TShirtType = {
    name?: string
    description: Map<string, string>
}

when I parse the JSON as TShirtType, I won't transform the description to the Map of <string, string>. I get an error tshirt.description.get is not a function.

const tshirt = JSON.parse(blob) as TShirtType
if (tshirt.description !== undefined) {
    console.log(tshirt.description)
    console.log(tshirt.description.get('S'))
}

I could define it as { [key: string]: string } and call tshirt.description['S'] to get value but I wish to use Map instead. I was wondering if this is possible.

negative0
  • 459
  • 4
  • 10
  • It is possible, but you'd have to provide [a custom reviver function](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/parse#Parameters) to take the object and instantiate a `Map` from it. – Heretic Monkey Apr 22 '20 at 21:02
  • @HereticMonkey I want to eliminate the use of `reviver` or any `callback` function to transform it to Map. I thought TypeScript would transform it automatically. For example generic types `Promise`. – negative0 Apr 22 '20 at 21:08
  • I would look at the answers to [How do I persist a ES6 Map in localstorage (or elsewhere)?](https://stackoverflow.com/q/28918232/215552), if you have control over the serialization. – Heretic Monkey Apr 22 '20 at 21:25
  • @HereticMonkey that is not answering this question, please provide an answer or reply when you have a valid one. – negative0 Apr 22 '20 at 21:26

0 Answers0