adplus-dvertising

No index signature with a parameter of type 'string' was found on type

Asked 3 years ago
Viewed 35.09 k times

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);
  });

asked 3 years ago

Correct Answer

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.

answered 2 years ago

Other Answer

You need to declare a Record Type

var map: Record<string, any> = {};

https://www.typescriptlang.org/docs/handbook/utility-types.html#recordkeystype

answered 3 years ago