简体   繁体   中英

How can I get the active flags of a flag enum in an object in Typescript?

As the title suggests, I'm wondering if there's a way to do a similar thing as in C# with flag enums , where if the object is printed to IO, it prints out the flags that are active, instead of an integer they accumulate to. Let's say I have a flag enum and an object with that enum as follows:

enum Weekdays {
 None = 0,
 Monday = 1 << 0,
 Tuesday = 1 << 1,
 Wednesday = 1 << 2, 
 Thursday = 1 << 3,
 Friday = 1 << 4,
 Saturday = 1 << 5,
 Sunday = 1 << 6
}
let obj = {
 workdays: Weekdays.Monday | Weekdays.Tuesday | Weekdays.Wednesday | Weekdays.Thursday | Weekdays.Friday
}

If I would to console.log this object now, I'd get the following:

{
 "workdays": 31
}

Of course I could iterate through the whole enum and check flags like that:

if ((obj.workdays & Weekdays.Monday) === Weekdays.Monday)

But that seems very inefficient, especially if I increase the size of the enum.

So the question is: Is there a more elegant way to check for active flags of an enum in an object?

I tried to write a generic function where I could just put an enum in and an object which values I want to check, but I didn't get far due to being pretty new to the language. I've also, naturally, searched the web for any solutions or at least hints of possible solutions, but couldn't find much except the flag check.

Since there's no such feature, I read some more documentation and tried implementing the solution myself. Here's the solution:

function getSelectedEnumMembers<T extends Record<keyof T, number>>(enumType: T, value: number): Extract<keyof T, string>[] {
    function hasFlag(value: number, flag: number): boolean {
        return (value & flag) === flag;
    }

    const selectedMembers: Extract<keyof T, string>[] = [];
    for (const member in enumType) {
        if (hasFlag(value, enumType[member])) {
        selectedMembers.push(member);
        }
    }
    return selectedMembers;
}

Hope it helps other people who somehow end up in my situation.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM