Categories
TypeScript Answers

How to add enum flags in TypeScript?

Spread the love

Sometimes, we want to add enum flags in TypeScript.

In this article, we’ll look at how to add enum flags in TypeScript.

How to add enum flags in TypeScript?

To add enum flags in TypeScript, we can assign the enum entries to binary values.

For instance, we write

enum Traits {
  None = 0,
  Friendly = 1 << 0,
  Mean = 1 << 1,
  Funny = 1 << 2,
  Boring = 1 << 3,
  All = ~(~0 << 4),
}

to assign each entry of Traits to binary values.

Then we can combine them with bitwise operators like

const traits = Traits.Mean | Traits.Funny;

Conclusion

To add enum flags in TypeScript, we can assign the enum entries to binary values.

Leave a Reply

Your email address will not be published.

If you like the content of this blog, subscribe to my email list to get exclusive articles not available to anyone else.