TypeScript 如何用变量作为键获取对象参数值并解决索引类型报错?
报错原因
该错误为TypeScript静态类型检查报错,不属于运行时错误。TypeScript会自动推导data对象的键为字面量联合类型 '001' | '002',而targetKey默认被推导为更宽泛的string类型,TS不允许用范围更大的string类型直接索引仅支持固定键的对象,因此抛出类型错误。
解决方法
- 方法1:约束
targetKey的类型为data的合法键类型
让targetKey的类型和data的键类型对齐,从根源避免类型不匹配问题:const data = { '001': { user: 'bob', age: 12 }, '002': { user: 'john', age: 5 } } // 用keyof typeof data自动获取data的键的联合类型 const targetKey: keyof typeof data = '001'; const result = data[targetKey]; console.log(result); - 方法2:给
data添加字符串索引签名
若data后续会动态添加任意字符串类型的键,可直接声明data支持所有字符串作为键:// 用Record声明key为string类型,value为对应结构的对象 const data: Record<string, {user: string, age: number}> = { '001': { user: 'bob', age: 12 }, '002': { user: 'john', age: 5 } } const targetKey = '001'; const result = data[targetKey]; console.log(result); - 方法3:临时类型断言
若确定当前targetKey一定是data的合法键,仅需临时绕过类型检查,可使用类型断言:const data = { '001': { user: 'bob', age: 12 }, '002': { user: 'john', age: 5 } } const targetKey = '001'; // 断言targetKey为data的合法键 const result = data[targetKey as keyof typeof data]; console.log(result);
内容的提问来源于stack exchange,提问作者alexlee11111
相关产品推荐
相关产品推荐

