Mityu
Mityu

Reputation: 163

Angular does not accept string variable as object key

Unfortunatelly I can't find answer or solution. So: if I use a static string as key, it works - but if I use a variable that gives exactly THE SAME string, Angular does not accept it.

The error message is weird: "Element implicitly has an 'any' type because expression of type 'string' can't be used to index type". (Of course this is NOT true, plus that is not index but key. Anyway.)

enter image description here

Thank for any help.

Upvotes: 0

Views: 920

Answers (2)

Osama Ansar
Osama Ansar

Reputation: 76

you should do something like

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

Upvotes: 1

nevzatopcu
nevzatopcu

Reputation: 1085

Obviously, It doesn't allow strings.

You should say that it's not an only string, it's one of the keys of the rendel object, so you should create a new interface and update the addItem function as the following

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


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

Upvotes: 1

Related Questions