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

时间:2021-07-26 09:55:34

标签: javascript typescript compiler-errors index-signature

在函数 getName 中,我遍历类 UnitGroups 的静态属性。该函数应返回适合传递值的属性标识符。例如。 UnitGroups.getName(1) 应该返回 "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;
        }
    }
}

我的代码完全正常,但打字稿抛出以下错误(将鼠标悬停在 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)

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

2 个答案:

答案 0 :(得分:1)

看起来 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

答案 1 :(得分:0)

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

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