Home > Back-end >  Angular does not accept string variable as object key
Angular does not accept string variable as object key

Time:05-18

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.

CodePudding user response:

you should do something like

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

CodePudding user response:

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
}

CodePudding user response:

not sure if this is what you want. you can change your code like this.

let obj :{[key: string]: any} = {a: 1}
  • Related