Skip to content

Instantly share code, notes, and snippets.

@th3d0g
Last active November 18, 2018 12:37
Show Gist options
  • Save th3d0g/f488c873233191e4811203f04538495e to your computer and use it in GitHub Desktop.
Save th3d0g/f488c873233191e4811203f04538495e to your computer and use it in GitHub Desktop.
Example of using 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) {
console.log(":(");
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment