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(":(");
}

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)