Skip to content

动态属性访问缺少索引签名

快速摘要

你用了 obj[dynamicKey] 但 obj 的类型没有索引签名 —— TypeScript 无法保证键存在。

为什么发生

  • 对象类型是特定接口无索引签名,你用变量键访问

  • 你用 Object.keys() 迭代键并尝试用每个键访问对象

  • 期望 Record 类型但提供了特定对象类型,缺少索引签名

最小示例

✗ 错误代码
const config = { host: 'localhost', port: 8080 };
const key = 'host';
console.log(config[key]); // error: no index signature
✓ 修复代码
const config = { host: 'localhost', port: 8080 };
const key = 'host' as keyof typeof config;
console.log(config[key]); // safe: config[key] is string | number

将键转换为 keyof typeof config 告诉 TypeScript 键是已知属性名之一,允许安全访问。

如何诊断

  • 阅读 TS 错误:'Element implicitly has an any type because type has no index signature'

  • 检查对象类型是否应使用 Record<string, T> 而非特定接口

  • 使用 keyof typeof obj 获取已知键并检查动态键是否为其中之一

如何修复

  • 为类型添加索引签名:{ [key: string]: ValueType; knownProp: string }

  • 将键转换为 keyof typeof obj:obj[key as keyof typeof obj]

  • 如果所有值同类型且需要动态访问则使用 Record<string, ValueType>

如何预防

  • 对需要动态字符串键访问的对象使用 Record<string, T>

  • 将 Object.keys() 结果类型化为 (keyof typeof obj)[] 并使用类型安全的键访问

相关资源

相关术语

相关课程

← 返回语言