Enums are for named constants#


Enums are used to represent sets of named constants. They improve the readability of our code and provide a means for defining numeric and string constants. Unlike the features covered so far, enums can be used as both type expressions and runtime expressions, meaning enums have a real value at runtime.

For this section, use the TypeScript Playground to examine the generated JavaScript as we define our enums. You'll notice that they have real values at runtime, and those values are determined by how we instantiate the enum.

In the example below, we represent HTTP status codes using an HTTP enum:

The logStatus() function accepts an HTTP member and prints a corresponding message depending on the given status code. When calling logStatus(), we have to use an HTTP enum member as the argument:


This page is a preview of Beginners Guide to TypeScript

No discussions yet