Enums in TypeScript

Photo by Kimson Doan on Unsplash

Enums in TypeScript

·

2 min read

For having different types of values associated with variable we can use an object and have keys attached to our requirement.

const MatchResult = {
    HomeWin: 'H';
    AwayWin : 'A';
    Draw : 'D';
}
// OR WE CAN DO THIS

const homeWin = 'H';
const awayWin = 'A';
const draw = 'D';

See how we declared a single object instead of 3 different variables.

Doing the same thing TypeScript with enums

Enum is short form for 'enumeration'. Enumeration is the action of mentioning a number of things one by one. In simple words, list, itemise all are synonyms of enumeration.

Enumeration is making a list of items we have

Enum is also an object that stores closely related values.

Refactoring object to an enum

To re-factor the JS object we declared in above sections into an enum, we will start by using the keyword 'enum' instead of const or let.

Now remove the equal sign = in front of object and replace it will : sign.

Inside the : sign in front of fields, replace it with = equal sign

Your enum is ready. Let's see a side by side comparison of JS object and TS enum

// JS object
const MatchResult = {
    HomeWin: 'H';
    AwayWin : 'A';
    Draw : 'D';
}

// TS enum
enum MatchResult  {
    HomeWin = 'H';
    AwayWin = 'A';
    Draw = 'D';
}

We can also declare enums without the equal sign = infront of keys.

enum MatchResult  {
    HomeWin, AwayWin, Draw
}

Accessing the enum values

Just like we access the object values, we will use the enum values as well.

MatchResult.HomeWin
MatchResult.Draw

More on enums

When we declare an enum, we are also declaring a new type in our TS code.

So we can now specify any variable, function input or output to be of MatchResult type.

We can declare some function that will return the MatchResult type. This is a sample function

const printMatchResult = () : MatchResult => {
    return MatchResult.Draw
}

The return type will always be one of the value from the enum else TS will throw an error

When to use enums?

Whenever our code requires a small set of values that are closely related to each other and can be grouped together and most importantly are known at the compile time, we will use enums.

Thankyou for reading. For more material on enums in TS, refer this https://www.typescriptlang.org/docs/handbook/enums.html