TypeScript enum example

TypeScript enums work basically how’d you’d expect from any normal language:

enum LogLevel {
  info, debug, error, critical, none

These are numbered sequentially, so you can use them like so:

if (level >= currentLevel) {

You can also set the numbers, as you’d expect:

enum LogLevel {
  info = 7, debug, error, critical, none

If you do this, the subsequent numbers will be 8, 9, etc.

Some documentation I’ve seen1 also recommends the use of these as flags, which is pretty neat as well (you see this a lot in code generated from other languages – e.g. ScalaJS or enscripten).

enum AnimalFlags {
    None           = 0,
    HasClaws       = 1 << 0,
    CanFly         = 1 << 1,
    EatsFish       = 1 << 2,
    Endangered     = 1 << 3

Interested in JavaScript? I send out weekly, personalized emails with articles and conference talks. Click here to see an example and subscribe.

  1. https://basarat.gitbooks.io/typescript/content/docs/enums.html []
0 replies

Leave a Reply

Want to join the discussion?
Feel free to contribute!

Leave a Reply

Your email address will not be published. Required fields are marked *