0

In my React Native + TypeScript app, I've defined a bunch of types as follows:

export type Streak = {
    ...
    marked: Map<number, string>
};

export type Habit = {
  ... 
  ...
  streak: Streak,
  ...
}

When I save Habit to AsyncStorage and read it back, I seem to be losing the Map type of the marked field, since I get marked back as an object {} type, and I cannot invoke functions like keys() or has() etc on marked.

await AsyncStorage.setItem(habit.key, JSON.stringify(habit));
....
....
let res = await AsyncStorage.getItem(habit.key);
let habit: Habit = JSON.parse(res); // I thought specifying the type Habit here would have given me `marked` back as a Map

if (habit.streak.marked.has(<someKey>)) { ... }

TypeError: ... marked.has is not a function ...

What should I be doing to preserve the Map type?

Shobit
  • 776
  • 1
  • 6
  • 20
  • 5
    You can't preserve it. It's the way JSON deserialization is implemented in JavaScript. You'll have to create the map again manually. You could of course create a [custom serializer](https://stackoverflow.com/questions/52895457/json-stringify-objects-custom-serializer) but I'd say that's overkill for this simple problem. – Mushroomator Feb 05 '23 at 21:46
  • Thank you! Bummer, but that's good to know. – Shobit Feb 05 '23 at 21:59

0 Answers0