我有一个像这样的 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 '{}'.
最佳答案
您只需向父字典添加适当的接口(interface),因为 typescript 会根据初始值自动分配类型,该初始值没有任何键
interface IParentDict {
[key: string]: any; // possibly change any to the typeof child dict
}
const parentDict: IParentDict = {};
关于javascript如何动态地将子字典附加到父字典,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60737087/