Canardlaquay Canardlaquay - 3 months ago 15
TypeScript Question

TypeScript union in enums

I've got a problem in TypeScript that I can't seem to solve.

Here's the code

enum test{
PowerAttack = 2,
MagicAttack = 5,
Attack = PowerAttack && MagicAttack //invalid

document.body.innerHTML = (test.PowerAttack == test.Attack).toString(); //check1
document.body.innerHTML += (test.MagicAttack == test.Attack).toString();//check2

How can I make the two checks work?

I am trying to make test.Attack be equal to test.PowerAttack AND test.MagicAttack, but I can't make it work.
Is it possible to do that with enums? Please note that I'll have many other entries in the enum, so I don't really want to mess with bitwise operators as it will get unreadable and unmaintainable pretty quickly.

If it's not possible to make it work with enums, what's the best logic to adopt? Classes and sub-classes? Types? Else?


Seems like you want to use enum values as flags. The simplest way to do it is to go with single bit binary numbers. e.g.

enum Test {
    PowerAttack = 1 << 0,
    MagicAttack = 1 << 1,
    Attack = PowerAttack | MagicAttack

Then you can test as:

var test: Test // you get this from somewhere
if (test & Test.Attack) {
    console.log('has attack');


This is covered here :