我有一个像这样的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 '{}'.
3 回答
九州编程
TA贡献1785条经验 获得超4个赞
let parentDict = {}这没有明确设置导致此问题的类型。尝试提供any如下类型:
let parentDict:any = {}或者,更准确地说:
let parentDict:{[key: string]: object} = {}
Smart猫小萌
TA贡献1911条经验 获得超7个赞
您只需向父字典添加适当的接口,因为打字稿会根据初始值自动分配类型,初始值没有任何键
interface IParentDict {
[key: string]: any; // possibly change any to the typeof child dict
}
const parentDict: IParentDict = {};
慕桂英546537
TA贡献1848条经验 获得超10个赞
像这样试试
let parentDict: any = {};
另一种选择可能是以更正确的方式指定类型,例如
let parentDict: {[key: string]: any} = {};
另一种骇人听闻的方式是
let parentDict = {}
for(let i = 0 ; i < 3; i++){
(parentDict as any)["place" + i] = childDict
}
添加回答
举报
0/150
提交
取消
