如何解决TypeScript构建动态属性名导入对象时的TS7053错误?
解决TypeScript TS7053索引类型错误
针对你遇到的问题,以下几种方法可以解决这个类型错误:
方法一:类型断言确认键的有效性
通过将循环中的component断言为MaterialPkg的键类型,让TypeScript确认它是合法的索引:
import * as MaterialPkg from '@mui/material' // 定义importObj的类型:键为string,值为MaterialPkg导出成员的类型 const importObj: Record<string, typeof MaterialPkg[keyof typeof MaterialPkg]> = {}; for (const component in MaterialPkg) { const typedComponent = component as keyof typeof MaterialPkg; const key = `@mui/material/${typedComponent}`; importObj[key] = MaterialPkg[typedComponent]; }
方法二:使用类型守卫
自定义类型守卫函数,在循环中校验component是否为MaterialPkg的有效键:
import * as MaterialPkg from '@mui/material' const importObj: Record<string, typeof MaterialPkg[keyof typeof MaterialPkg]> = {}; // 类型守卫:判断传入的key是否是MaterialPkg的键 function isMaterialComponentKey(key: string): key is keyof typeof MaterialPkg { return key in MaterialPkg; } for (const component in MaterialPkg) { if (isMaterialComponentKey(component)) { const key = `@mui/material/${component}`; importObj[key] = MaterialPkg[component]; } }
方法三:给MaterialPkg添加索引签名断言
直接断言MaterialPkg支持任意string索引,适合不需要严格类型校验的场景:
import * as MaterialPkg from '@mui/material' const importObj: Record<string, any> = {}; // 断言MaterialPkg同时具备原类型和string索引签名 const typedMaterialPkg = MaterialPkg as typeof MaterialPkg & { [key: string]: any }; for (const component in typedMaterialPkg) { const key = `@mui/material/${component}`; importObj[key] = typedMaterialPkg[component]; }
错误原因说明
TypeScript中for...in循环的变量默认类型为string,但@mui/material导出的类型没有定义任意string索引签名,TypeScript无法确认任意string都是合法的索引键,因此触发TS7053错误。上述方法都是通过类型断言或守卫,让TypeScript确认索引的合法性,从而消除错误。
内容的提问来源于stack exchange,提问作者antun
相关产品推荐
相关产品推荐

