0

Let's say I have an two enums Side and SideDecider and in the latter one I have a key side which should be a value of Side so that when I use SideDecider.side I know it is a value of Side.

enum Side {
  left,
  right,
}

enum SideDecider {
  random,
  other,
  side, // = Side.left | Side.right is what I would like to use
}

// I am looking for a solution resolving something like the following to true
console.log(Side.left === SideDecider.side || Side.right === SideDecider.side)
// error: This condition will always return 'false' since the types 'Side.left' and 'SideDecider.side' have no overlap.

How would I correctly yield such a usage. Am I trying to incorrectly use enums? Thank you for your help in advance.

Check out example at TypeScript Playground

EDIT

What I'm actually trying to achieve is the same but using the enums as strings so I can use these as keys for objects, see my second example. Here, someone recommends using a class for string based enums. Is this best practice?

enum Side {
  left = 'left',
  right = 'right',
}

enum SideDecider {
  random = 'random',
  other = 'other',
  side = Side.left | Side.right // Error: Computed values are not permitted in an enum with string valued members
}

const testObj = {
  left: 'something',
  right: 'something',
}

// (1) I am looking for a solution resolving something like the following to [true, true]
console.log([Side.left && SideDecider.side, Side.right && SideDecider.side])

// (2) Is there a way to use SideDecider.side to access keys in testObj?
console.log(testObj[SideDedicer.side])
7
  • console.log(+Side.left === SideDecider.side || +Side.right === SideDecider.side) works. Commented Jun 21, 2019 at 11:01
  • But then [+Side.left === SideDecider.side, +Side.right === SideDecider.side] resolves to [false, true] which I would like to resolve to [true, true] Commented Jun 21, 2019 at 11:09
  • Oh, my bad, I think you are looking for flag enums (which need to be powers of 2). console.log((Side.left & SideDecider.side) != 0 || (Side.right | SideDecider.side) !== 0) typescript-play.js.org/#code/… Commented Jun 21, 2019 at 11:15
  • So when using the SideDecider enum as a key for an Object, I should probably write a function evaluationg these power of 2 enums? I have lots of these use cases so I am really looking forward to doing this a best practices way. Commented Jun 21, 2019 at 11:43
  • Not necessarily, numbers are valid keys for an object. You would have been using numbers as keys with regular enums as well, the only difference would have been that that they would have been consecutive numbers Commented Jun 21, 2019 at 11:45

0

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.