Can you cast a key from a for in loop as a property from an interface?

Viewed 205

In trying to set a property on an object where the value is coming from a dynamically generated form, I’m using a for in loop to find a property in the object and set it

   FormFeatureArray.forEach((el) => {

     // form handling stuff omitted
      For(const key in myObject){
        If(key === el.feature){
          myObject.key = formInputField.value
            }
           }
       })

This of course throws ts(2339) to which I would like to be able cast key as a property of myObject, but I can’t know which property of the interface key is referring to, so is there a way to cast key as a guaranteed property of the interface of myObject, or override the warning for that line? Something like this is what I’m looking for

myObject.(key as aPropertyOfMyObject) = formInputField.value

The interface for myObject would be some like

Interface MyObjects {
Name: string
A: number
B: number 
C: number 
}

And key can be matching any of those properties of myObject, depending on the field of the form being selected, which is at runtime

1 Answers

you want the key to be typed as keyof MyObject for the behaviour you are looking for, you could do something like this:

const objKeys = Object.keys(myObject) as (keyof typeof myObject)[];
for (const key of objKeys) {
    if (key === el.feature) {
        myObject[key] = formInputField.value;
    }
}

note that you need to use myObject[key], using myObject.key is equivalent to myObject["key"] which is probably not what you intend. Also since you just need to see if el.feature is one of the keys you could skip the for loop entirely by doing this:

const objKeys = Object.keys(myObject);
if (objKeys.includes(el.feature)) {
    myObject[el.feature as keyof typeof myObject] = formInputField.value;
}
Related