Typescript Enums

Photo by Joan Gamell on Unsplash

Typescript Enums

What are enums?

Typescript enums provide a way to define a set of named constants. Let's have a look at how we can use them in our code.

Declare an enum

Let's imagine a user of our app needs to select the colour of their car when they are configuring a new build. We could declare an Colour enum with three constants Red, Green and Blue.

enum Colour {
    Red,
    Green,
    Blue
}

Colour is a numeric enum. Red has a value of 0, Green has a value of 1 and Blue has a value of 2. All values of type number. Numeric enums, by default, begin with the value 0.

Numeric enums may be provided with a start value.

enum Colour {
    Red = 1,
    Green,
    Blue
}

Now Colour, while still a numeric enum, assigns the value 1 to Red, Green will be assigned the value 2 and Blue assigned the value 3.

Numeric enums may have an assignment for all enum values.

enum Colour {
    Red = 1,
    Green = 2,
    Blue = 3
}

Numeric enums can have a mix of computed and constant members. However, all constant members will have to come before all computed members.

enum Colour {
    Red,
    Green = 2,
    Blue = calcBlueValue()
}

Typescript also supports string enums. String enum members must be constants initialized with a string literal.

enum Colour {
    Red = "RED",
    Green = "GREEN",
    Blue = "BLUE"
}

Using an enum

Accessing an enum member value is done via dot notation.

enum Colour {
    Red,
    Green,
    Blue
}

console.log(Colour.Red) // 0
console.log(Colour.Green) // 1
console.log(Colour.Blue) // 2

Conclusion

Enums are an elegant way to document code intent. The Colour enum could have been string constants instead, however, their purpose would be less apparent and their close relationship less than obvious.

Happy coding!!!