What are enum Flags in TypeScript?

They're a way to efficiently store and represent a collection of boolean values.

For example, taking this flags enum:

enum Traits {
    None = 0,
    Friendly = 1 << 0, // 0001 -- the bitshift is unnecessary, but done for consistency
    Mean = 1 << 1,     // 0010
    Funny = 1 << 2,    // 0100
    Boring = 1 << 3,   // 1000
    All = ~(~0 << 4)   // 1111
}

Instead of only being able to represent a single value like so:

let traits = Traits.Mean;

We can represent multiple values in a single variable:

let traits = Traits.Mean | Traits.Funny; // (0010 | 0100) === 0110

Then test for them individually:

if ((traits & Traits.Mean) === Traits.Mean) {
    console.log(":(");
}

The official documentation has this example that I will add some details that are crucial to use enum and flags.

enum FileAccess {
    None,
    Read    = 1 << 1,
    Write   = 1 << 2,
}

In TypeScript, you can assign a value directly with =

let x:FileAccess = FileAccess.Read;

But this might override previous values. To get around that you can use |= to append a flag.

x |= FileAccess.Write;

At this point, the variable x is Read and Write. You can remove a value by using the ampersand and tilde:

x &= ~FileAccess.Read;

Finally, you can compare to see if one of the value is set to the variable. The accepted answer is not right. It should not just use the ampersand symbol but also check with === to the desired value. The reason is the ampersand returns a number, not a boolean.

console.log(FileAccess.Write === (x & FileAccess.Write)); // Return true
console.log(FileAccess.Read === (x & FileAccess.Read)); // Return false

Tags:

Typescript