为什么打字稿在这里抛出索引签名错误?

Why typescript throws an index-signature error here?

在函数 getName 中,我循环访问 class UnitGroups 的静态属性。该函数应该 return 属性 的标识符适合传递的值。例如。 UnitGroups.getName(1) 应该 return "Speed".


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) {
            const number = UnitGroups[property];
            if (number === unitGroup) return property;
        }
    }
}

我的代码完全可以正常工作,但 typescript 抛出以下错误(将鼠标悬停在 UnitGroups[property] 上时出现):

Element implicitly has an 'any' type because expression of type 'string' can't be used to index type 'typeof UnitGroups'.
  No index signature with a parameter of type 'string' was found on type 'typeof UnitGroups'.ts(7053)

我不明白错误和错误信息...

您不能通过 class 进行循环,请改用 thisthis 是一个特殊的词,它链接到上下文的一个对象上。在classes中this表示这个class的对象。 试试这个

public static getName(unitGroup: number) {
    for (const property in this) {
        const number = this[property];
        if (number === unitGroup) return property;
    }
}

看起来 TypeScript 没有正确推断 for..in 循环中的类型。

您可以为编译器添加一个提示,如下所示:

const number = UnitGroups[property as keyof UnitGroups];

或者,对于您的特定情况,您可以使用枚举来实现相同的行为:

enum UnitGroupType {
    Length = 0,
    Speed = 1,
    Area = 2,
    // ...
}

function getName(type: UnitGroupType) {
    return UnitGroupType[type]
}

playground link

more about enums