TypeScript使用方括号访问对象属性报undefined不能作为索引类型如何解决?
修复方案
问题本质
TypeScript 报错核心原因有两个:
cred.name的类型包含null/undefined,而对象索引仅支持 string/number/symbol 类型,不能直接用可能为空的值作为索引- 若
state未定义索引签名,即使cred.name是字符串,TS 也会判定字符串不一定是state的合法键
方案1:空值过滤(最安全,运行时也兼容)
先做空值判断,过滤掉name为空的 credential,TS 会自动收窄类型:
for (const cred of provider.credentials || []) { const credId = cred.id const credName = cred.name // 新增类型守卫,不符合条件直接跳过当前循环 if (typeof credName !== 'string') continue const credValue = state[credName] }
方案2:正确使用非空断言(仅适合确定cred.name绝对不为空的场景)
注意非空断言!要直接加在可能为空的变量后面:
for (const cred of provider.credentials || []) { const credId = cred.id // 赋值时就加非空断言,告诉TS这个值一定不会为空 const credName = cred.name! const credValue = state[credName] }
额外处理:state索引类型报错
如果以上操作后依然报错,说明你的state没有声明合法的索引类型,有两种解决方式:
- 给state加索引签名,放开键的类型限制:
// 声明state的键为字符串,值为字符串,适配任意合法的cred.name const state: Record<string, string> = { cred1: 'value', cred2: 'value' }
- 若要严格限制state的键,把cred.name的类型关联为state的键的联合类型:
// 自动提取state的所有键作为合法的name类型 type StateKey = keyof typeof state // 定义credential的类型时指定name的类型 interface Credential { id: string name: StateKey }
内容的提问来源于stack exchange,提问作者Esteban Vargas
相关产品推荐
相关产品推荐

