为什么TypeScript遍历类静态属性时抛出索引签名错误ts(7053)?
错误触发原因
TypeScript 中for...in遍历得到的键默认是string类型,而你定义的UnitGroups类没有声明支持任意字符串作为索引签名,因此 TypeScript 无法确定string类型的property一定是UnitGroups的合法静态属性,就抛出了ts(7053)错误。
解决方法
最简单的方案是给遍历得到的键加上类型断言,明确告诉 TypeScript 这个键是UnitGroups的合法静态属性名。这里用到的keyof typeof UnitGroups会自动生成UnitGroups所有静态属性名的联合类型(也就是"Length" | "Speed" | "Area" | ...),用它作为property的类型,TypeScript 就能识别它是合法的索引值,不会再报错。
修改后的代码如下:
export default class UnitGroups { static Length = 0; static Speed = 1; static Area = 2; static Mass = 3; static Volume = 4; static VolumeFlowRate = 5; static Temperature = 6; static Time = 7; static Acceleration = 8; static Charge = 9; static Force = 10; static Voltage = 11; static Power = 12; static Energy = 13; static Pace = 14; static Pressure = 15; static Illuminance = 16; static PartsPer = 17; static Current = 18; static ApparentPower = 19; static ReactivePower = 20; static ReactiveEnergy = 21; static Angle = 22; static Digital = 23; static Frequency = 24; public static getName(unitGroup: number) { for (const property in UnitGroups) { // 加类型断言,明确property是UnitGroups的合法静态属性名 const propertyKey = property as keyof typeof UnitGroups const number = UnitGroups[propertyKey]; if (number === unitGroup) return property; } } }
如果想要更严谨,也可以先把UnitGroups的所有键转成明确类型的数组再遍历:
public static getName(unitGroup: number) { const unitKeys = Object.keys(UnitGroups) as Array<keyof typeof UnitGroups> for (const key of unitKeys) { const value = UnitGroups[key] if (value === unitGroup) return key } }
内容的提问来源于stack exchange,提问作者MeineHTMLCodes
相关产品推荐
相关产品推荐

