0

I have COLOR enum declared as below..

export declare enum COLOR {
    RED = "RED",
    BLUE = "BLUE",
    YELLOW = "YELLOW"
}


interface IProps {
  config?: {
    disallowedColors: COLOR;
  };

now i need to access the value config.disallowedColors. If i want to pass multiple colors to config.disallowedColors, how do i do that ?? for e.g. i want config.disallowedColors = red, yellow

Can someone please shed some light here.

1
  • 2
    COLOR[] or Array<COLOR> ? Commented Jan 22, 2020 at 22:17

1 Answer 1

3

Given the enum values are string, a simple array would suffice i.e. config.disallowedColors = [COLOR.RED, COLOR.YELLOW].

When checking, you can leverage includes / some etc. to check if a flag is set e.g.

config.disallowedColors.includes(COLOR.RED);

It gets slightly more complicated when you need to check for multiple values, one option would be to create a temp array for the values you want to check are present, and then leverage every comparing each one to the target array i.e.

const flags = [COLOR.RED, COLOR.YELLOW];
const { disallowedColors } = config;
flags.every(c => disallowedColors.includes(c));

Alternatively, if you used a numerical value then you could leverage Bitwise Operations to create a bit mask which would give you the same result (just in a different way) i.e.

// values should be ^2
enum COLOR {
  NONE = 0
  RED = 1,
  BLUE = 2,
  YELLOW = 4,
  ...
}
...
// setting multiple flags
const colors = COLOR.RED | COLOR.YELLOW;
// check for existence of single flag
const isRed = (colors & COLOR.RED) === COLOR.RED;
// check for existence of multiple flags
const flags = COLOR.RED | COLOR.YELLOW;
const hasMultiple = (colors & flags) === flags; 
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.