首页 > 解决方案 > 在类型上找不到带有“字符串”类型参数的索引签名

问题描述

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

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

元素隐式具有“任何”类型,因为“字符串”类型的表达式不能用于索引“对象”类型。

在“Object”.ts(7053) 类型上找不到带有“string”类型参数的索引签名

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

标签: node.jstypescriptdictionarygoogle-cloud-firestore

解决方案


您通常不想使用new Object(). 相反,map像这样定义:

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

如果可以的话,最好any用更具体的东西替换,但这应该可以开始。


推荐阅读