在类型

时间:2019-09-03 10:43:53

标签: node.js typescript dictionary google-cloud-firestore

我来自移动应用程序开发,对打字稿没有太多经验。如何声明[string:any]形式的地图对象?

错误出现在行:map [key] = value;

  

元素隐式地具有“ any”类型,因为类型“ string”的表达式不能用于索引类型“ 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 个答案:

答案 0 :(得分:4)

您通常不想使用new Object()。而是像这样定义map

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

如果可以的话,最好将any替换为更具体的内容,但是从一开始就应该起作用。

答案 1 :(得分:4)

您需要声明一个记录类型

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

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

答案 2 :(得分:1)

如上所述,@ Tim Perry,直接使用对象。我建议您建立自己的字典。

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

那么您就可以使用

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

哪个更容易阅读。