0

I am trying to read data from Firestore into my TypeScript Project.

In Firestore I have a Map under the field mapName

The following data structure I got while using JSON.stringify(change.after.data())

const test: Test = {
  mapName: {
    "v3mioXc3VoFgfj0WEq": {
      isNormalSubscription: false,
    },
    "as12oXc3VoFas12WEq": {
      isNormalSubscription: true,
    },
  },
};

interface Test {
  mapName: Map<string, any>
}

I am getting though the following error:

Type '{ v3mioXc3VoFgfj0WEq: { isNormalSubscription: false; }; }' is not assignable to type 'Map<string, any>'.
  Object literal may only specify known properties, and '"v3mioXc3VoFgfj0WEq"' does not exist in type 'Map<string, any>'.

Since v3mioXc3VoFgfj0WEq and as12oXc3VoFas12WEq are Firestore Keys that I do not know beforehand, how should I change my Test interface to properly manage the data?

Georgios
  • 861
  • 2
  • 12
  • 30

1 Answers1

2

Firestore does not accept or return ES6 Map type object. It only works with plain old JavaScript objects. When you call data() on a DocumentSnapshot, you get one of these plain objects. The properties of the object match the fields in the document.

const obj = snapshot.data()   // plain object
const mapName = obj.mapName   // another plain object
const field1 = mapName.v3mioXc3VoFgfj0WEq
const field2 = mapName.as12oXc3VoFas12WEq

If you would rather work with a Map object, you will have to convert the plain object into a new Map.

Doug Stevenson
  • 297,357
  • 32
  • 422
  • 441
  • I would like to iterate through the mapName field without knowing the "keys". If I got this right from your above code, is this not possible? – Georgios Sep 17 '20 at 15:33
  • That's a different question (iterating properties of an object), and it has lots of different answers already. https://stackoverflow.com/questions/8312459/iterate-through-object-properties – Doug Stevenson Sep 17 '20 at 15:41
  • I did not know that I could just iterate through this data structure. I had in mind that I should have an array structure for that. This helped. – Georgios Sep 17 '20 at 16:00
  • How to define the interface for a map? – Zaffer May 08 '23 at 19:58