How to Compare Enum strings or numbers in typescript?

Typescripts Enum compare: This tutorial explains how we can compare Enum Strings and numbers in Angular and typescript.

In this tutorial, How to compare the String with Enum value in typescript/javascript.

The below examples use the comparison operator !== and === operators for checking enum equality.

You can check my other posts on typescript Enum object.

How to Compare Enum Strings values in Typescript?

In the below example, Enum is declared for color. Enum contains a string property name and value.

Multiple ways we can compare Enum values with strings.

  • Compare using Triple Equal Operator

=== operator is used to check string against with Enum Object.

By default, the triple equal operator is applied to the same two operands of the same type. In the following example, a string and value are checked and compared, and type conversion is used. String object is compared with Enum Object directly

export enum Color {
  RED = "#FF0000",
  GREEN = "#008000",
  YELLOW = "#FFFF00",
  BLUE = "#0000FF",
  MAROON = "#800000",
}
console.log(Color.RED); //#FF0000
function isColorRed(color: string) {
  if (color === Color.RED) {
    return true;
  }
  return false;
}

console.log(isColorRed("#FF0000")); //true
console.log(isColorRed("RED")); // false

Another way, Convert to String using toSting() and compare it.

// Convert the enum value to a string and compare
if (Color.RED.toString() === str) {
  return true;
} else {
  return false;
}

Final way , use type assertion to treat Enum as a string value, compare it

//  type assertion to compare
if (Color.RED as unknown as string === str) {
    return true;
} else {
    return false;
}

  • Use Switch Case

Switch used to execute code statements for a case match. It accepts Enum value in Switch and case contains a string.

const str: string = '#FF0000';
switch (Color.RED) {
  case str:
    console.log('Red');
    break;
  default:
    console.log('Other color');
    break;
}

How to Compare Numbers in enum type in Typescript?

By default, enum holds numeric values if a string value is defined.

In the below example, Enum is declared with constants, but not its value. Numbers are assigned (A=0, B=1, C=2, D=3).

Here the number is compared against Enum numeric values.

Here is an example

export enum Chars {
  A,
  B,
  C,
  D,
}
console.log(Chars.A); //0
function isA(char: number) {
  if (char === Chars.A) {
    return true;
  }
  return false;
}

console.log(isA(1)); //false
console.log(isA(0)); // true

Conclusion

To Sum up, Learn How to compare enum strings and values in Typescript with examples.