How to use string to access the values of a typed object?

Viewed 51

I have an object that looks like this

interface ProvideFeedbackFormProps {
  feedbackNature: FormikDropdownProps
  waybillNumber: FormikDropdownProps
  provideFeedback: FormikDropdownProps
  editorState?: string
  attachments?: string[]
}

and FormikDropdownProps looks like this

interface FormikDropdownProps {
  id: number
  value: string
}

When I run a loop on data that implements the above structure (values below is of type ProvideFeedbackFormProps), like so

for (const property in values) {
  const customField = values[property]
  customFields.push(customField)
}

I get an error at values[property] that says

Element implicitly has an 'any' type because expression of type 'string' can't be used to index type 'ProvideFeedbackFormProps'.
  No index signature with a parameter of type 'string' was found on type 'ProvideFeedbackFormProps'

Questions

  1. What is causing this behavior?
  2. How can I fix it?
2 Answers
for (const property in values) { // property here will be typed as string
  const customField = values[property]
  customFields.push(customField)
}

The property value will be typed as a string. You can be more explicit and cast it to the correct type:

for (const property in values) {
  const customField = values[property as keyof ProvideFeedbackFormProps]
  customFields.push(customField)
}

Using the keyof keyword will cast the property type to be a key of ProvideFeedbackFormProps

You can follow the discussion on this issue on Github

If you encounter typing error, "any" can be used as a universal type.

for (const property in values) {
    const any_values = values as any;
    const customField = any_values[property]
    customFields.push(customField)
}
Related