20
votes

I'm coming from mobile app development and do not have much experience with typescript. How one can declare a map object of the form [string:any] ?

The ERROR comes at line: map[key] = value;

Element implicitly has an 'any' type because expression of type 'string' can't be used to index type 'Object'.

No index signature with a parameter of type 'string' was found on type 'Object'.ts(7053)

 var docRef = db.collection("accidentDetails").doc(documentId);


 docRef.get().then(function(doc: any) {
   if (doc.exists) {
      console.log("Document data:", doc.data());
      var map = new Object();
      for (let [key, value] of Object.entries(doc.data())) {
        map[key] = value;

       // console.log(`${key}: ${value}`);
      }
  } else {
      // doc.data() will be undefined in this case
      console.log("No such document!");
  } }).catch(function(error: any) {
      console.log("Error getting document:", error);
  });
3

3 Answers

60
votes

You generally don't want to use new Object(). Instead, define map like so:

var map: { [key: string]: any } = {}; // A map of string -> anything you like

If you can, it's better to replace any with something more specific, but this should work to start with.

7
votes
4
votes

As @Tim Perry mentioned above, use object directly. What I would recommend is to build your own dictionary.

declare global {
   type Dictionary<T> = { [key: string]: T };
}

Then you would be able to use

const map: Dictionary<number> = {} // if you want to store number.... 

Which is easier to read.