TypeScript Enums Tutorial with Examples

In this tutorial, we will learn TypeScript enums with examples.
In TypeScript, enums are set of named constants. Though it is optional, enums should be a named group of related constants. TypeScript supports both traditional enums and string-based enums.

Table of contents

1. Typescript String-based Enums
2. Traditional Number-based Enums
3. Heterogeneous Enum
4. const enums
5. Enum with static functions

1. Typescript String-based Enums

In a string enum, each member has to be constant-initialized with a string literal, or with another string enum member.
Check out enums in Java at Java Enums Tutorial.
Enum syntax is very similar to other languages e.g. Java.
// Example 2 - String-based Enums
enum Direction {
    Up = "UP",
    Down = "DOWN",
    Left = "LEFT",
    Right = "RIGHT",
}

1.1 Typescript String-based Enums Examples

Example 1: How to create enum in Typescript

Let's create a typescript file named enums.ts and add following code to it:
// Example 2 - String-based Enums
enum Direction {
    Up = "UP",
    Down = "DOWN",
    Left = "LEFT",
    Right = "RIGHT",
}

// Access enum member values
console.log(Direction.Up);
console.log(Direction.Down);
console.log(Direction.Left);
console.log(Direction.Right);

console.log(Direction['Up']);
console.log(Direction['Down']);

Example 2: How to access enum member values

Use Enum.member or Enum['member'] format to access enum member values. For Example:
console.log(Direction.Up);
console.log(Direction.Down);
console.log(Direction['Up']);
console.log(Direction['Down']);
Let's run above typescript file using following command:
c:\user\typescript-tutorial> tsc .\enums.ts
Look at the generated code in JavaScript. It has a generated lookup table like this.
var Direction;
(function (Direction) {
    Direction["Up"] = "UP";
    Direction["Down"] = "DOWN";
    Direction["Left"] = "LEFT";
    Direction["Right"] = "RIGHT";
})(Direction || (Direction = {}));
// Access enum member values
console.log(Direction.Up);
console.log(Direction.Down);
console.log(Direction.Left);
console.log(Direction.Right);
console.log(Direction['Up']);
console.log(Direction['Down']);
The above file created as enums.js file. Now we don't need a browser, we can use node.js to run this javascript file. Let's run this enums.js file using the following command:
c:\user\typescript-tutorial> node .\enums.js
UP
DOWN
LEFT
RIGHT
UP
DOWN
Follow similar steps to run below typescript examples.

Example 3: LogLevel Enum

// Example 1- String-based Enums
export enum LogLevel {
    Off = "Off",
    Fatal = "Fatal",
    Error = "Error",
    Warn = "Warn",
    Info = "Info",
    Debug = "Debug"
}

// Access enum member values
console.log(LogLevel.Debug);
console.log(LogLevel.Error);
console.log(LogLevel.Warn);
console.log(LogLevel.Info);
console.log(LogLevel.Fatal);

console.log(LogLevel['Fatal']);
console.log(LogLevel['Debug']);
console.log(LogLevel['Info']);

Example 4: Weekday Enum

// Example 3 - String-based Enums
enum Weekday {
    Monday = "Monday",
    Tuesday = "Tuesday",
    Wednesday = "Wednesday",
    Thursday = "Thursday",
    Friday = "Friday",
    Saturday = "Saturday",
    Sunday = "Sunday"
}

// Access enum member values
console.log(Weekday.Monday);
console.log(Weekday.Tuesday);
console.log(Weekday.Wednesday);
console.log(Weekday.Thursday);
console.log(Weekday.Friday);
console.log(Weekday.Saturday);
console.log(Weekday.Sunday);

console.log(Weekday['Saturday']);
console.log(Weekday['Sunday']);

Example 5: Enum as a function argument

To pass enum in functions, declare the argument type of enum itself.
enum Direction {
    Up = "UP",
    Down = "DOWN",
    Left = "LEFT",
    Right = "RIGHT",
}

function checkDirection(direction: Direction){
    console.log(direction);
}

checkDirection(Direction.Up);
checkDirection(Direction.Down);
checkDirection(Direction.Left);
checkDirection(Direction.Right);
Output:
C:\user\typescript-tutorial> tsc .\enums.js
C:\user\typescript-tutorial> node .\enums.js
UP
DOWN
LEFT
RIGHT

2. Traditional Number-based Enums

TypeScript enums are number based. This means that numbers can be assigned to an instance of the enum, and so can anything else that is compatible with a number.
Though not recommended, you may come across situations where you need it. So let’s quickly learn.

2.1 Example: How to create number-based enums

In below example, we have not initialized the values, transpiler generates a lookup table with values assigned in array index fashion (starting with zero and then incrementing by one for each member).
enum Weekday {
    Monday,
    Tuesday,
    Wednesday,
    Thursday,
    Friday,
    Saturday,
    Sunday
}

// Access enum member values
console.log(Weekday.Sunday);
console.log(Weekday['Sunday']);
console.log(Weekday[0]);
Output:
C:\user\typescript-tutorial> tsc .\enums.js
C:\user\typescript-tutorial> node .\enums.js
6
6
Monday

2.2 Access enum member values

As these are number based enums, you can use the format enum[index_number] as well, along with Enum.member or Enum['member'].
// Access enum member values
console.log(Weekday.Sunday);
console.log(Weekday['Sunday']);
console.log(Weekday[0]);
If you want to start with any other number, then assign it to the first enum member. All following members will get the value by incrementing one by one.
In below example, we start at 1 and start incrementing from there:
enum Weekday {
    Monday = 1,
    Tuesday ,
    Wednesday,
    Thursday,
    Friday,
    Saturday,
    Sunday
}

2.3 Enum as a function argument

To pass enum in functions, declare the argument type of enum itself.
enum Weekday {
    Monday,
    Tuesday,
    Wednesday,
    Thursday,
    Friday,
    Saturday,
    Sunday
}


function test(weekday: Weekday){
    console.log(weekday);
}

test(Weekday.Sunday);
test(Weekday.Monday);

3. Heterogeneous enum

Technically enums can be mixed with string and numeric members, but it’s not clear why you would ever want to do so:
enum BooleanLikeHeterogeneousEnum {
    No = 0,
    Yes = "YES",
}
Unless you’re really trying to take advantage of JavaScript’s runtime behavior in a clever way, it’s advised that you don’t do this.

4. Typescript const enums

In most cases, enums are a perfectly valid solution. However, sometimes requirements are tighter. To avoid paying the cost of extra generated code and additional indirection when accessing enum values, it’s possible to use const enums. Const enums are defined using the const modifier on our enums:
const enum Direction {
    Up = "UP",
    Down = "DOWN",
    Left = "LEFT",
    Right = "RIGHT",
}

5. Enum with static functions

You can use the declaration enum + namespace merging to add static methods to an enum. The following demonstrates an example where we add a static member isBusinessDay to an enum Weekday:
enum Weekday {
    Monday,
    Tuesday,
    Wednesday,
    Thursday,
    Friday,
    Saturday,
    Sunday
}
namespace Weekday {
    export function isBusinessDay(day: Weekday) {
        switch (day) {
            case Weekday.Saturday:
            case Weekday.Sunday:
                return false;
            default:
                return true;
        }
    }
}

const mon = Weekday.Monday;
const sun = Weekday.Sunday;
console.log(Weekday.isBusinessDay(mon)); // true
console.log(Weekday.isBusinessDay(sun)); // false

6. Conclusion

In this tutorial, we have seen how to create TypeScript string and number based enums with lots of examples. We have also seen, heterogeneous and const enums with an examples.

Learn more about TypeScript at TypeScript Tutorial with Examples.

7. References

Comments

  1. Most useful Typescript enums examples. Recommended tutorial.

    ReplyDelete

Post a Comment