How to Compare Enum strings or numbers in typescript with example

In this tutorial post, We are going to compare the String with Enum value in typescript/javascript

The below examples uses the comparision operator !== and === operator for checking enum equality

 Compare Strings value exists in Enum of Typescript

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

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

By default, triple equal operator applied of same two operands of the same type

In the below example, string and enum value are checked as it uses type conversion two typescript

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

Compare Number in enum type in Typescript

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

In the below example, Chars 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 {
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

– Thanks Kiran

Similar Posts