使用typescript从接口映射对象中的json数据



我正试图将Excel工作表中的数据放入json对象中。为此,我创建了一个用于读取excel的结构Info对象,以及一个用于应该接收数据的对象的Thing接口。正如你所看到的,它们有1:1的属性名称Thing:excelStructure.structure

export const excelStructure: { [key: string]: any } = {
"headerRow": 1,
"firstdatarow": 3,
"structure": {
"sortierung": "A",
"stockwerk": "B",
"raum": "C",
"objekt": "D",
"typ": "E",
"aktor": "F",
"aktorausgang": "G",
"ga_schalten": "H",
"ga_dimmer": "I",
"ga_helligkeit": "J",
"ga_schaltzustand": "K",
"ga_wert": "L",
"groups": "M",
"allow_export": "N"
}
}

export interface Thing{
sortierung: string
stockwerk: string
raum: string
objekt: string
typ: string
aktor: string
aktorausgang: string
ga_schalten: string
ga_dimmer: string
ga_helligkeit: string
ga_schaltzustand: string
ga_wert: string
groups: string
allow_export: string
}

现在我想创建一个循环,在其中我从excel读取数据并填充Thing对象。

var dataObject:Thing = {
...excelStructure.structure
} //to initialize the Thing object with something. Don´t know if I need it :-(

for (const key in excelStructure.structure) {
dataObject[excelStructure.structure[key]] = sh.getRow(idx).getCell(excelStructure.structure[key]).value

IDE抱怨道:

Element implicitly has an 'any' type because expression of type 'any' can't be used to index type 'Thing'.ts(7053)

有没有一种平滑的方法可以做到这一点,而不必将其属性映射到自己的属性?

谢谢大家!

您可以尝试使用keyof typeof dataObject

for (const key in excelStructure.structure) {
let objKey = key as keyof typeof dataObject;
dataObject[objKey] = /* value */;
}

示例打字游戏场

注意:excelStructure.structure[key]返回值,但不返回key

dataObject[objKey] = sh.getRow(idx).getCell(key).value as string

成功了!。谢谢@勇顺!

最新更新