{

How to check String/Number exists in enum in typescript


check String/Number exists in enum in typescript

Enum is a new datatype introduced in Javascript/typescript which holds strings or numbers only.

Sometimes, It is necessary to check whether a declared string or number exists in an Enum object.

This blog post covers checking whether string or number value exists in Enum in javascript or typescript

You can check my other posts on typescript Enum object

How to Check if String exists in Enum of values in Typescript?

There are many ways we can check string exists in an enumeration

  • Using ES7 Array Includes method

ES7, the latest javascript language introduced includes method.

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

Object.values() method is ES6 method that accepts enum or objects 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 approach will not work if the provided value is a number.

How to check Number exists in the enum in typescript?

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 a string with number values.

In typescript, the Enum object holds the following format 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 checked in enum in many ways

  • using in operator An enum is an object, In operator returns true if a property exists in an object, else returns false
  • Enum index syntax - return strings if the 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

Conclusion

In Conclusion, Learned how to check if a string or number exists in a typescript enum with examples.

THE BEST NEWSLETTER ANYWHERE
Join 6,000 subscribers and get a daily digest of full stack tutorials delivered to your inbox directly.No spam ever. Unsubscribe any time.

Similar Posts
Subscribe
You'll get a notification every time a post gets published here.