在TypeScript中如何通过变量名访问对象的索引属性?
错误原因
你定义routes时未显式声明类型,TypeScript 会自动推导它的类型为字面量类型:{ "/": {}; "/abc": {}; },该类型的合法键只有"/"和"/abc"两个字符串字面量,而非任意字符串。
你声明的indextoFind变量默认被推导为通用string类型,string的取值范围远大于routes的合法键范围,TypeScript 无法确保这个字符串变量一定是routes的合法键,因此抛出类型错误。
而直接写routes["/abc"]时,传入的是固定字符串字面量,TypeScript 可以直接识别它属于routes的合法键,因此不会报错。
解决方案
- 方案1:限定索引变量的类型为
routes的合法键集合
如果你确定变量取值只会是routes已有的键,可以直接用keyof typeof routes限定变量类型:const indextoFind: keyof typeof routes = "/abc"; const item = routes[indextoFind]; - 方案2:给
routes添加字符串索引签名
如果routes的键本身就是任意动态字符串,可以在声明时显式指定索引类型:// Record<string, {}> 表示键为string类型,值为空对象类型 const routes: Record<string, {}> = { "/": {}, "/abc": {}, }; const indextoFind = "/abc"; const item = routes[indextoFind]; - 方案3:使用类型断言跳过校验
如果你确认当前变量取值一定是合法键,不想修改前面的类型定义,可以临时用类型断言告知TypeScript校验逻辑:const indextoFind = "/abc"; const item = routes[indextoFind as keyof typeof routes];
如果索引变量是动态获取的(比如来自接口返回、用户输入),建议先加运行时判断再访问,避免运行时错误:
const indextoFind = getDynamicPath(); // 动态获取的路径 if (indextoFind in routes) { const item = routes[indextoFind as keyof typeof routes]; }
内容的提问来源于stack exchange,提问作者qscott86
相关产品推荐
相关产品推荐

