Given:
Enum: {1, 4, 16}
Flags: 20
When: I pass Flags to a function
Then:
I get array of flags of given Enum: [4, 16]
Note: I have tried to convert Enum to array manually and treat values as numbers. But I get overwhelmed when it gets to TS and I want to make that function dynamic in case Enum gets changed. I really don't want hardcode that. Please help!
enum Enum {
one = 1,
four = 4,
sixteen = 16,
}
const Flags: number = 20;
function getEnumValues(flags: number): Enum[] {
const enumFlags = [1, 4, 16];
const enums: Enum[] = [];
enumFlags.forEach(ef => {
if ((ef & flags) != 0) {
enums.push(ef);
}
})
return enums;
}
console.log(getEnumValues(Flags));
Solution found here: Typescript flagged enum get values Is not good because my Enum is not a sequence 2 and 8 is missing.