javascript - 如何使用字符串访问类型化对象的值?
问题描述
我有一个看起来像这样的对象
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'
问题
- 是什么导致了这种行为?
- 我该如何解决?
解决方案
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上关注这个问题的讨论
推荐阅读
- java - 从另一个方法调用数组
- python - Python Flask 模板更新
- syntax-error - 重塑长多个变量时出错
- javascript - 当没有标识每一行的 ID 时,如何删除包含文件名的每一行(一次)?
- c - 数组的最小和分区
- elasticsearch - 仅使用 Logstash 向 ES 发送新数据,防止重复
- azure - Amazon Rekognition 或 Azure Cognitive Face 是否可以用于基于人脸识别的考勤系统
- php - 为什么这个 php 接口代码有效?
- sql - 错误返回所选日期
- c# - 使用下拉菜单索引删除列表成员正在删除保存数据中的整个列表