javascript - 接口(interface)上类型 'string' 的索引签名无法识别( typescript )

标签 javascript typescript

我有这个代码:

const sectionInstance: FieldValues = sectionInstances[i]
for (const field in sectionInstance) {
    console.log(sectionInstance[field])
}
这里的

field当然是一个字符串。以下是 FieldValues 的类型定义:

export interface FieldValues = {
  [key: string]: FieldValue;
}

我仍然收到此错误:

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

我不是已经为接口(interface) FieldValues 声明了“字符串”类型的索引签名吗?为什么我会收到此错误?

最佳答案

只需从接口(interface)定义中删除 = 即可。

Please take a look at playground

interface FieldValues {
  [key: string]: FieldValue;
}
...
const sectionInstance: FieldValues = sectionInstances[i];
for (const field in sectionInstance) {
  console.log(sectionInstance[field]);
}

关于javascript - 接口(interface)上类型 'string' 的索引签名无法识别( typescript ),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63218725/

相关文章:

Angular 2拖放上传

typescript - 如何在 typescript 中为类动态添加装饰器

javascript - 从 Material-UI 实现日历,在我的一个组件中使用 Hooks

javascript - Power BI Embedded - 访问 token

javascript - ASP.Net GridView JavaScript 弹出模式窗口 - 设置透明度?

javascript - 在 Angular 6 项目中,@brief 是什么意思?

javascript - hogan.js + Jade ?

javascript - 如何构造一个 Promise 来调用其中的异步函数,解析结果,然后解析/拒绝?

image - 从 dataDirectory 文件路径设置为 img 的 src

javascript - Angular 2 中推荐的服务架构