How to check String/Number exists in enum in typescript
- Admin
- Mar 6, 2024
- Typescript Javascript
Enum is a new data type 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 how to check if a string or number value exists in an Enum in JavaScript or TypeScript.
You can also check out my other posts on TypeScript Enum objects.
How to Check if a String Exists in Enum Values in TypeScript?
There are several ways we can check if a string exists in an enumeration.
- Using ES7 Array Includes Method
ES7
, the latest javascript language introduced
In ES7, the latest JavaScript language introduced the includes method.
enum WeekEndMap {
Sunday = "sunday",
Saturday = "saturday"
}
The Object.values()
method is an ES6 method that accepts an enum or objects and returns an array of enum strings.
The includes()
method simply checks and returns true if the string exists, and false if it does not.
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 if a Number Exists in the Enum in TypeScript?
Let’s declare an Enum
for the 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:
key <--> value
value <--> key
Printing the enum object.
{ '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 an enum
in several ways:
- Using the in operator: An enum is an object, and the in operator returns true if a property exists in an object, otherwise it returns false.
- Enum index syntax: Returns strings if the number exists, otherwise returns undefined.
let numberValue = 1;
console.log(numberValue in Weeks); //true
console.log(Weeks[numberValue]); //MONDAY
console.log(Weeks[10]); // undefined
if (Weeks[numberValue]) {
console.log("Number exists");
}
if (!Weeks[10]) {
console.log("Number does not exist");
}
and console output is
true
MONDAY
undefined
number exists
number exists
Conclusion
In conclusion, you’ve learned how to check if a string or number exists in a TypeScript enum with examples.