What are enum Flags in TypeScript?

后端 未结 5 1242
死守一世寂寞
死守一世寂寞 2021-01-30 17:08

I\'m learning TypeScript using this ebook as a reference. I\'ve checked the TypeScript Official Documentation but I don\'t find information about enum flags.

5条回答
  •  太阳男子
    2021-01-30 17:33

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

提交回复
热议问题