【问题标题】:javascript how to dynamically append child dicts to a parent dictjavascript如何动态地将子字典附加到父字典
【发布时间】:2020-03-18 09:57:03
【问题描述】:

我有一个像这样的 Javascript 对象:

const childDict = {
  address: {
    zip: "GGHG654",
    city: "Morocco",
    number: 40
  }
}

我想像这样在循环中动态地将它添加到另一个父字典中:

let parentDict = {}

for(let i = 0 ; i < 3; i++){
  parentDict["place" + i] = childDict
}

所以最后我得到了一个这样的字典:

{
  place0: {
    address: {
      zip: "GGHG654",
      city: "Morocco",
      number: 40
    }
  },
  place1: {
    address: {
      zip: "GGHG654",
      city: "Morocco",
      number: 40
    }
  }
}

然而,for 循环给了我一个编译错误:

Element implicitly has an 'any' type because expression of type 'string' can't be used to index type '{}'.
  No index signature with a parameter of type 'string' was found on type '{}'.

【问题讨论】:

  • 当前代码有什么问题?
  • @palaѕн parentDict["place" + i] 给出编译错误。我编辑了问题以包含错误。
  • 只循环到 childDict 项目的长度

标签: javascript typescript dictionary javascript-objects


【解决方案1】:

您只需向父字典添加适当的接口,因为打字稿会根据初始值自动分配类型,它没有任何键

interface IParentDict {
    [key: string]: any; // possibly change any to the typeof child dict
}
const parentDict: IParentDict = {};

【讨论】:

    【解决方案2】:
    let parentDict = {}
    

    这没有明确设置导致此问题的类型。尝试提供any 类型,例如:

    let parentDict:any = {}
    

    或者,更准确地说:

    let parentDict:{[key: string]: object} = {}
    

    【讨论】:

      【解决方案3】:

      您的解决方案很有效,您只需将 parentDict 的类型指定为任何类型。 您是否尝试在 for 循环之后执行 console.log(parentDict)

      【讨论】:

        【解决方案4】:

        这样试试

        let parentDict: any = {};

        另一种选择可能是以更正确的方式指定类型,例如

        let parentDict: {[key: string]: any} = {};

        另一种 hacky 方式是

        let parentDict = {}
        
        for(let i = 0 ; i < 3; i++){
            (parentDict as any)["place" + i] = childDict
        }
        

        【讨论】:

          猜你喜欢
          • 2018-12-27
          • 2023-02-24
          • 1970-01-01
          • 1970-01-01
          • 2012-02-14
          • 2021-05-17
          • 2019-06-29
          • 1970-01-01
          • 2020-12-06
          相关资源
          最近更新 更多