user3019647
user3019647

Reputation: 153

How to pass multiple enum values to a variable in ReactJs typescript

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.

Upvotes: 0

Views: 3139

Answers (1)

James
James

Reputation: 82136

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; 

Upvotes: 3

Related Questions