How to check String/Number exists in enum of javascript/typescript


Enum is a new datatype introduced in Javascript/typescript which holds strings or numbers only. Some times  It is necessary to check whtether declared string or number exists in a Enum. This blog post covers checking string or number value exists in Enum in javascript or typescript

You can also check my previous about typescript Enum

Check Strign exists in Enum values

There are many ways we can check string exists in enumeration

Using ES7 Array Includes method

ES7, latest javascript language introduced includes method.

enum WeekEndMap {
Sunday = "sunday",
Saturday = "saturday"
}

Object.values() method is ES6 method which accepts enum or object returns array of enum string includes() method simply checks and returns true -if exists, false- not exists.

const list=Object.values(WeekEndMap);
console.log(list)//[ 'sunday', 'saturday' ]
console.log(typeof list); // object
if (Object.values(WeekEndMap).includes('sunday')) {
console.log("string exists")
}

This apporach will not work if provided value is number.

How to check Number exists in enum, typescript/Javascript

let us declare Enum for week

export enum Weeks {
    MONDAY = 1,
    TUESDAY= 2,
    WEDNESDAY = 3,
    THURSDAY = 4,
    FRIDAY = 5,
    SATURDAY=6,
    SUNDAY=7,
}

Enum is declared which holds string with number values.

In typescript, Enum object holds the following format as below

key <--> value
value <-->  key

Printing the enum object as follows

{ '1': 'MONDAY',
  '2': 'TUESDAY',
  '3': 'WEDNESDAY',
  '4': 'THURSDAY',
  '5': 'FRIDAY',
  '6': 'SATURDAY',
  '7': 'SUNDAY',
  MONDAY: 1,
  TUESDAY: 2,
  WEDNESDAY: 3,
  THURSDAY: 4,
  FRIDAY: 5,
  SATURDAY: 6,
  SUNDAY: 7 }

Numbers can be check in enum in many ways

  • using in operator Enum is an object, In operator returns true if property exists in an object,else return false
  • Enum index syntax - return strings if number exists, else undefined returned
let numberValue=1
console.log(numberValue in Week) //true
console.log(Week[numberValue]) //MONDAY
console.log(Week[10])  // undefined
if (Week[numberValue]) {
  console.log("number exists")
}
if (!Week[10]) {
  console.log("number not exists")
}

and console output is

true
MONDAY
undefined
number exists
number exists
Similar Posts