0

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...

MeineHTMLCodes
  • 509
  • 5
  • 19

2 Answers2

1

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

  • Thanks! Your first approach works perfectly fine! I know I could use an enum, but I want to make the groups extensible with a clean syntax (e.g. 'class MyCustomUnitGroups extends UnitGroups'), which is why I'm sticking with the static class attributes. – MeineHTMLCodes Jul 26 '21 at 10:12
0

You can't make loop through class, use this instead. this is a speacial word, that links on an object of the context. In classes this means object of this class. Try this

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