Categories
TypeScript Answers

How to compare enums in TypeScript?

Spread the love

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.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *