【问题标题】:No index signature with a parameter of type 'string' was found on type在类型上找不到带有“字符串”类型参数的索引签名
【发布时间】:2020-01-06 06:22:30
【问题描述】:

我来自移动应用程序开发,对打字稿没有太多经验。如何声明 [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.js typescript dictionary google-cloud-firestore


    【解决方案1】:

    你需要声明一个记录类型

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

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

    【讨论】:

      【解决方案2】:

      正如上面提到的@Tim Perry,直接使用对象。我的建议是建立自己的字典。

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

      然后你就可以使用了

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

      哪个更容易阅读。

      【讨论】:

        【解决方案3】:

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

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

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

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2021-10-16
          • 2019-10-27
          • 2021-11-27
          • 1970-01-01
          • 2021-12-04
          • 1970-01-01
          • 1970-01-01
          • 2019-11-18
          相关资源
          最近更新 更多