首页 > 解决方案 > 如何使用字符串访问类型化对象的值?

问题描述

我有一个看起来像这样的对象

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

FormikDropdownProps看起来像这样

interface FormikDropdownProps {
  id: number
  value: string
}

当我对实现上述结构的数据运行循环时(values下面是类型ProvideFeedbackFormProps),就像这样

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

我得到一个错误values[property]

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'

问题

  1. 是什么导致了这种行为?
  2. 我该如何解决?

标签: javascripttypescript

解决方案


for (const property in values) { // property here will be typed as string
  const customField = values[property]
  customFields.push(customField)
}

property值将作为字符串键入。您可以更明确并将其转换为正确的类型:

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

使用keyof关键字会将属性类型转换为ProvideFeedbackFormProps

你可以在 Github上关注这个问题的讨论


推荐阅读