Angular 不接受字符串变量作为对象键

Angular does not accept string variable as object key

很遗憾,我找不到答案或解决方案。 所以:如果我使用静态字符串作为键,它会起作用 - 但如果我使用给出完全相同字符串的变量,Angular 不接受它。

错误消息很奇怪:“元素隐式具有 'any' 类型,因为 'string' 类型的表达式不能用于索引类型”。 (当然这不是真的,而且那不是索引而是键。无论如何。)

感谢您的帮助。

显然,它不允许字符串。

你应该说它不是唯一的字符串,它是 rendel 对象的键之一,所以你应该创建一个新接口并更新 addItem 函数如下

interface Rendel {
    alap: string,
    tipus: string,
    felfet: string
}


addItem(adat: {v: string, kulcs: keyof Rendel}) {
        this.rendel[adat.kulcs] = adat.v
}

你应该这样做

this.rendel[adat.kulcs as keyof typeof this.rendel] = adat.v