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) {
  onLog(message);
}

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
}

If you want a good Javascript book, I got a lot out of Secrets of the Javascript Ninja.

Citations:
  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 *