Andrei Enache
Andrei Enache

Reputation: 537

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

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

Upvotes: 33

Views: 71320

Answers (3)

aWebDeveloper
aWebDeveloper

Reputation: 38392

You need to declare a Record Type

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

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

Upvotes: 14

Pierre-Louis Lacorte
Pierre-Louis Lacorte

Reputation: 363

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.

Upvotes: 7

Tim Perry
Tim Perry

Reputation: 13256

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.

Upvotes: 89

Related Questions