无法识别接口上“字符串”类型的索引签名(打字稿)

时间:2020-08-02 16:57:01

标签: javascript typescript

我有此代码:

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

field当然是字符串。这是FieldValues的类型定义:

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

仍然出现此错误:

元素隐式地具有“ any”类型,因为类型的表达式 'string'不能用于索引类型'FieldValues'。没有索引 在类型上找到参数类型为“字符串”的签名 'FieldValues'.Vetur(7053)

我不是为interface FieldValues声明了'string'类型的索引签名吗?为什么会出现此错误?

2 个答案:

答案 0 :(得分:2)

只需从接口定义中删除=

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]);
}

答案 1 :(得分:0)

据我所知,Typescript无法从[key: string]推断键类型。仅在尝试概括某些键(可能是其他键除外)可能具有字符串类型时,此功能才有用。 TS无法确保您在for中访问的密钥是您在string中使用的类型[key: string]。您应该明确地说出来。