How to compare enums in TypeScript?

Sometimes, we want to compare enums in TypeScript.

In this article, we’ll look at how to compare enums in TypeScript.

How to compare enums in TypeScript?

To compare enums in TypeScript, we can assign a value to each enum so we can compare them easily.

For instance, we write

enum AnimalInfo {
  Tiger = "Tiger",
  Lion = "Lion",
}

let tigerStr = "Tiger";

if (tigerStr === AnimalInfo.Tiger) {
  console.log("true");
} else {
  console.log("false");
}

to create the AnimalInfo enum which has values assigned to each entry.

Then we compare tigerStr to AnimalInfo.Tiger with tigerStr === AnimalInfo.Tiger.

AnimalInfo.Tiger is 'Tiger' since we assigned 'Tiger‘ to Tiger in AnimalInfo.

Conclusion

To compare enums in TypeScript, we can assign a value to each enum so we can compare them easily.