Search code examples
typescriptenumsenum-flags

Pass / Get multiple Enum values in Typescript?


Pass value which is the combination of enum values and get the corresponding enum strings of it.

Here is my scenario,

enum EnumDays {
    NONE = 0,
    SUN = 1,
    MON = 2,
    TUE = 4,
    WED = 8,
    THU = 16,
    FRI = 32,
    SAT = 64,
    ALL = 127
}

I'll pass the value as 5, which is the combination of SUN & TUE (1 + 4 = 5).

I want to get "SUN" & "TUE" as result. How to achieve this?


Solution

  • This can be done either by iterating through bits or by iterating through enum members. Iterating through bits seems a little cleaner. We take advantage of the fact that EnumDays maps values to keys (e.g., 1 to SUN) as well as keys to values (SUN to 1). (Nit: This approach won't find an enum value of 2147483648. 1 << 31, which is -2147483648, will work.)

    function getDayNames(value: EnumDays) {
        let names = [];
        for (let bit = 1; bit != 0; bit <<= 1) { 
            if ((value & bit) != 0 && bit in EnumDays) { 
                names.push(EnumDays[bit]);
            }
        }
        return names;
    }