Canard
Canard

Reputation: 67

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?

Upvotes: 1

Views: 2582

Answers (2)

basarat
basarat

Reputation: 276313

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');
}

More

This is covered here : https://basarat.gitbooks.io/typescript/content/docs/enums.html#enums-as-flags

Upvotes: 2

user663031
user663031

Reputation:

I assume you want

enum test{
    PowerAttack = 2,
    MagicAttack = 5,
    Attack = PowerAttack | MagicAttack
}

We define test.Attack as the bitwise or of the two other values, in other words 7.

Now test.PowerAttack and test.MagicAttack can be tested for "membership" in test.Attack by saying test.PowerAttack & test.Attack. If you want bit-based enums, you can't avoid using & to test inclusion--that's just how you have to do it.

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

Upvotes: 1

Related Questions