javascripttypescriptcompiler-errorsindex-signature

Why typescript throws an index-signature error here?


In the function getName I loop through the static properties of the class UnitGroups. The function should return the property's identifier fitting to the passed value. E.g. UnitGroups.getName(1) should 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;
        }
    }
}

My code works completely fine but typescript throws following error (appears when hovering over 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)

I don't understand the error and the error message...


Solution

  • Looks like TypeScript does not infer type in the for..in loop correctly.

    You can add a hint for the compiler as follows:

    const number = UnitGroups[property as keyof UnitGroups];
    

    Alternatively, for your particular case you can use an enum to implement the same behaviour:

    enum UnitGroupType {
        Length = 0,
        Speed = 1,
        Area = 2,
        // ...
    }
    
    function getName(type: UnitGroupType) {
        return UnitGroupType[type]
    }
    

    playground link

    more about enums