Tutorial: Checking Enum Value Existence in TypeScript

Avatar

By squashlabs, Last Updated: Oct. 14, 2023

Tutorial: Checking Enum Value Existence in TypeScript

Definition of Enum in TypeScript

In TypeScript, an enum is a way to define a set of named constants. It allows you to create a group of related values that can be used as a single type. Enums are useful when you want to represent a fixed set of values that are mutually exclusive.

Here is an example of an enum in TypeScript:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
enum Color {
Red,
Green,
Blue,
}
enum Color { Red, Green, Blue, }
enum Color {
Red,
Green,
Blue,
}

In this example, we define an enum called

Color
Color with three values:
Red
Red,
Green
Green, and
Blue
Blue. Each value is assigned a numeric value starting from 0 by default. So, in this case,
Red
Red is 0,
Green
Green is 1, and
Blue
Blue is 2.

Enums can also have string values assigned explicitly:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
enum Color {
Red = "RED",
Green = "GREEN",
Blue = "BLUE",
}
enum Color { Red = "RED", Green = "GREEN", Blue = "BLUE", }
enum Color {
Red = "RED",
Green = "GREEN",
Blue = "BLUE",
}

Now,

Red
Red is assigned the string value "RED",
Green
Green is assigned "GREEN", and
Blue
Blue is assigned "BLUE".

Related Article: How to Merge Objects in TypeScript

Creating Enum Types in TypeScript

To create an enum type in TypeScript, you simply use the

enum
enum keyword followed by the name of the enum and the values enclosed in curly braces. Each value is separated by a comma.

Here is an example of creating an enum type in TypeScript:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
enum Direction {
North,
East,
South,
West,
}
enum Direction { North, East, South, West, }
enum Direction {
North,
East,
South,
West,
}

In this example, we define an enum type called

Direction
Direction with four values:
North
North,
East
East,
South
South, and
West
West. Each value is assigned a numeric value starting from 0 by default.

You can also explicitly assign numeric or string values to enum values:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
enum Direction {
North = 1,
East = 2,
South = 3,
West = 4,
}
enum Direction { North = 1, East = 2, South = 3, West = 4, }
enum Direction {
North = 1,
East = 2,
South = 3,
West = 4,
}

In this example,

North
North is assigned the numeric value 1,
East
East is assigned 2,
South
South is assigned 3, and
West
West is assigned 4.

Accessing Enum Values in TypeScript

Once you have defined an enum in TypeScript, you can access its values using dot notation.

Here is an example of accessing enum values in TypeScript:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
enum Color {
Red,
Green,
Blue,
}
let color: Color = Color.Red;
console.log(color); // Output: 0
let colorName: string = Color[1];
console.log(colorName); // Output: "Green"
enum Color { Red, Green, Blue, } let color: Color = Color.Red; console.log(color); // Output: 0 let colorName: string = Color[1]; console.log(colorName); // Output: "Green"
enum Color {
Red,
Green,
Blue,
}

let color: Color = Color.Red;
console.log(color); // Output: 0

let colorName: string = Color[1];
console.log(colorName); // Output: "Green"

In this example, we define an enum called

Color
Color with three values:
Red
Red,
Green
Green, and
Blue
Blue. We then create a variable
color
color and assign it the value
Color.Red
Color.Red. When we log
color
color to the console, it displays the numeric value 0, which corresponds to
Red
Red.

We can also access the enum values using their numeric values. In the second part of the example, we create a variable

colorName
colorName and assign it the value
Color[1]
Color[1]. When we log
colorName
colorName to the console, it displays the string value "Green", which corresponds to the numeric value 1.

Checking if a Value Exists in an Enum

In TypeScript, there are several ways to check if a value exists in an enum. One common approach is to create a helper function that iterates over the enum values and checks if the given value matches any of them.

Here is an example of checking if a value exists in an enum using a helper function:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
enum Color {
Red,
Green,
Blue,
}
function isValueInEnum(value: number, enumObject: any): boolean {
for (let key in enumObject) {
if (enumObject[key] === value) {
return true;
}
}
return false;
}
let valueExists: boolean = isValueInEnum(1, Color);
console.log(valueExists); // Output: true
valueExists = isValueInEnum(4, Color);
console.log(valueExists); // Output: false
enum Color { Red, Green, Blue, } function isValueInEnum(value: number, enumObject: any): boolean { for (let key in enumObject) { if (enumObject[key] === value) { return true; } } return false; } let valueExists: boolean = isValueInEnum(1, Color); console.log(valueExists); // Output: true valueExists = isValueInEnum(4, Color); console.log(valueExists); // Output: false
enum Color {
Red,
Green,
Blue,
}

function isValueInEnum(value: number, enumObject: any): boolean {
for (let key in enumObject) {
if (enumObject[key] === value) {
return true;
}
}
return false;
}

let valueExists: boolean = isValueInEnum(1, Color);
console.log(valueExists); // Output: true

valueExists = isValueInEnum(4, Color);
console.log(valueExists); // Output: false

In this example, we define an enum called

Color
Color with three values:
Red
Red,
Green
Green, and
Blue
Blue. We then create a helper function
isValueInEnum
isValueInEnum that takes a value and an enum object as arguments. The function iterates over the keys of the enum object and checks if the corresponding value matches the given value. If a match is found, the function returns
true
true, otherwise it returns
false
false.

We use the

isValueInEnum
isValueInEnum function to check if the value
1
1 exists in the
Color
Color enum. The first call to
isValueInEnum
isValueInEnum returns
true
true because
Green
Green has the numeric value
1
1. The second call to
isValueInEnum
isValueInEnum returns
false
false because there is no enum value with the numeric value
4
4.

Related Article: Tutorial on Typescript ts-ignore

Using Conditional Statements to Check Enum Values

Another way to check if a value exists in an enum is to use conditional statements. You can use the

switch
switch statement or a series of
if
if statements to compare the value with each enum value.

Here is an example of using a

switch
switch statement to check if a value exists in an enum:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
enum Color {
Red,
Green,
Blue,
}
function isValueInEnum(value: number, enumObject: any): boolean {
switch (value) {
case enumObject.Red:
case enumObject.Green:
case enumObject.Blue:
return true;
default:
return false;
}
}
let valueExists: boolean = isValueInEnum(1, Color);
console.log(valueExists); // Output: true
valueExists = isValueInEnum(4, Color);
console.log(valueExists); // Output: false
enum Color { Red, Green, Blue, } function isValueInEnum(value: number, enumObject: any): boolean { switch (value) { case enumObject.Red: case enumObject.Green: case enumObject.Blue: return true; default: return false; } } let valueExists: boolean = isValueInEnum(1, Color); console.log(valueExists); // Output: true valueExists = isValueInEnum(4, Color); console.log(valueExists); // Output: false
enum Color {
Red,
Green,
Blue,
}

function isValueInEnum(value: number, enumObject: any): boolean {
switch (value) {
case enumObject.Red:
case enumObject.Green:
case enumObject.Blue:
return true;
default:
return false;
}
}

let valueExists: boolean = isValueInEnum(1, Color);
console.log(valueExists); // Output: true

valueExists = isValueInEnum(4, Color);
console.log(valueExists); // Output: false

In this example, we define an enum called

Color
Color with three values:
Red
Red,
Green
Green, and
Blue
Blue. We then create a helper function
isValueInEnum
isValueInEnum that takes a value and an enum object as arguments. The function uses a
switch
switch statement to compare the value with each enum value. If a match is found, the function returns
true
true, otherwise it returns
false
false.

We use the

isValueInEnum
isValueInEnum function to check if the value
1
1 exists in the
Color
Color enum. The first call to
isValueInEnum
isValueInEnum returns
true
true because
Green
Green has the numeric value
1
1. The second call to
isValueInEnum
isValueInEnum returns
false
false because there is no enum value with the numeric value
4
4.

Performing a Lookup of a Value in an Enum

In TypeScript, you can perform a lookup of a value in an enum by using the enum's key or value.

Here is an example of performing a lookup of a value in an enum using the key:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
enum Color {
Red = "RED",
Green = "GREEN",
Blue = "BLUE",
}
function findValueByKey(key: string, enumObject: any): string | undefined {
for (let enumKey in enumObject) {
if (enumKey === key) {
return enumObject[key];
}
}
return undefined;
}
let value: string | undefined = findValueByKey("Green", Color);
console.log(value); // Output: "GREEN"
value = findValueByKey("Yellow", Color);
console.log(value); // Output: undefined
enum Color { Red = "RED", Green = "GREEN", Blue = "BLUE", } function findValueByKey(key: string, enumObject: any): string | undefined { for (let enumKey in enumObject) { if (enumKey === key) { return enumObject[key]; } } return undefined; } let value: string | undefined = findValueByKey("Green", Color); console.log(value); // Output: "GREEN" value = findValueByKey("Yellow", Color); console.log(value); // Output: undefined
enum Color {
Red = "RED",
Green = "GREEN",
Blue = "BLUE",
}

function findValueByKey(key: string, enumObject: any): string | undefined {
for (let enumKey in enumObject) {
if (enumKey === key) {
return enumObject[key];
}
}
return undefined;
}

let value: string | undefined = findValueByKey("Green", Color);
console.log(value); // Output: "GREEN"

value = findValueByKey("Yellow", Color);
console.log(value); // Output: undefined

In this example, we define an enum called

Color
Color with three values:
Red
Red,
Green
Green, and
Blue
Blue. Each value is assigned a string value. We then create a helper function
findValueByKey
findValueByKey that takes a key and an enum object as arguments. The function iterates over the keys of the enum object and checks if the key matches the given key. If a match is found, the function returns the corresponding value, otherwise it returns
undefined
undefined.

We use the

findValueByKey
findValueByKey function to perform a lookup of the value for the key "Green" in the
Color
Color enum. The function returns the string value "GREEN". We also perform a lookup of the value for the key "Yellow", which is not present in the enum, so the function returns
undefined
undefined.

Techniques for Validating Enum Values

When working with enums in TypeScript, there are several techniques you can use to validate enum values.

One common technique is to use the

hasOwnProperty
hasOwnProperty method to check if an enum has a particular key. This method returns a boolean indicating whether the object has the specified property.

Here is an example of validating enum values using the

hasOwnProperty
hasOwnProperty method:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
enum Color {
Red,
Green,
Blue,
}
function isValidEnumValue(value: any, enumObject: any): boolean {
return Object.keys(enumObject).some((key) => enumObject[key] === value);
}
let isValid: boolean = isValidEnumValue("Green", Color);
console.log(isValid); // Output: true
isValid = isValidEnumValue("Yellow", Color);
console.log(isValid); // Output: false
enum Color { Red, Green, Blue, } function isValidEnumValue(value: any, enumObject: any): boolean { return Object.keys(enumObject).some((key) => enumObject[key] === value); } let isValid: boolean = isValidEnumValue("Green", Color); console.log(isValid); // Output: true isValid = isValidEnumValue("Yellow", Color); console.log(isValid); // Output: false
enum Color {
Red,
Green,
Blue,
}

function isValidEnumValue(value: any, enumObject: any): boolean {
return Object.keys(enumObject).some((key) => enumObject[key] === value);
}

let isValid: boolean = isValidEnumValue("Green", Color);
console.log(isValid); // Output: true

isValid = isValidEnumValue("Yellow", Color);
console.log(isValid); // Output: false

In this example, we define an enum called

Color
Color with three values:
Red
Red,
Green
Green, and
Blue
Blue. We then create a helper function
isValidEnumValue
isValidEnumValue that takes a value and an enum object as arguments. The function uses the
Object.keys
Object.keys method to get an array of the enum object's keys. It then uses the
some
some method to iterate over the keys and check if the corresponding value matches the given value. If a match is found, the function returns
true
true, otherwise it returns
false
false.

We use the

isValidEnumValue
isValidEnumValue function to validate the value "Green" in the
Color
Color enum. The first call to
isValidEnumValue
isValidEnumValue returns
true
true because
Green
Green is a valid enum value. The second call to
isValidEnumValue
isValidEnumValue returns
false
false because "Yellow" is not a valid enum value.

Built-in Methods for Enum Value Validation

TypeScript provides built-in methods that can be used for enum value validation. These methods include

Object.values
Object.values,
Object.keys
Object.keys, and
Object.entries
Object.entries.

Here is an example of using the

Object.values
Object.values method to validate enum values:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
enum Color {
Red,
Green,
Blue,
}
let values: string[] = Object.values(Color);
console.log(values); // Output: ["Red", "Green", "Blue"]
let isValid: boolean = values.includes("Green");
console.log(isValid); // Output: true
isValid = values.includes("Yellow");
console.log(isValid); // Output: false
enum Color { Red, Green, Blue, } let values: string[] = Object.values(Color); console.log(values); // Output: ["Red", "Green", "Blue"] let isValid: boolean = values.includes("Green"); console.log(isValid); // Output: true isValid = values.includes("Yellow"); console.log(isValid); // Output: false
enum Color {
Red,
Green,
Blue,
}

let values: string[] = Object.values(Color);
console.log(values); // Output: ["Red", "Green", "Blue"]

let isValid: boolean = values.includes("Green");
console.log(isValid); // Output: true

isValid = values.includes("Yellow");
console.log(isValid); // Output: false

In this example, we define an enum called

Color
Color with three values:
Red
Red,
Green
Green, and
Blue
Blue. We use the
Object.values
Object.values method to get an array of the enum values. The
Object.values
Object.values method returns an array containing the values of the enum. We then use the
includes
includes method to check if the given value is included in the array of enum values. If the value is found, the
includes
includes method returns
true
true, otherwise it returns
false
false.

We use the

includes
includes method to validate the value "Green" in the
Color
Color enum. The first call to
includes
includes returns
true
true because
Green
Green is a valid enum value. The second call to
includes
includes returns
false
false because "Yellow" is not a valid enum value.

Related Article: How to Verify if a Value is in Enum in TypeScript

Libraries and Packages for Enum Value Checking

There are several libraries and packages available for enum value checking in TypeScript. These libraries provide additional functionality and convenience methods for working with enums.

One popular library is

enum-utils
enum-utils, which provides utility functions for working with enums, including value checking.

Here is an example of using the

enum-utils
enum-utils library for enum value checking:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
import { containsValue } from "enum-utils";
enum Color {
Red,
Green,
Blue,
}
let contains: boolean = containsValue(Color, "Green");
console.log(contains); // Output: true
contains = containsValue(Color, "Yellow");
console.log(contains); // Output: false
import { containsValue } from "enum-utils"; enum Color { Red, Green, Blue, } let contains: boolean = containsValue(Color, "Green"); console.log(contains); // Output: true contains = containsValue(Color, "Yellow"); console.log(contains); // Output: false
import { containsValue } from "enum-utils";

enum Color {
Red,
Green,
Blue,
}

let contains: boolean = containsValue(Color, "Green");
console.log(contains); // Output: true

contains = containsValue(Color, "Yellow");
console.log(contains); // Output: false

In this example, we import the

containsValue
containsValue function from the
enum-utils
enum-utils library. We define an enum called
Color
Color with three values:
Red
Red,
Green
Green, and
Blue
Blue. We then use the
containsValue
containsValue function to check if the given value is present in the
Color
Color enum. If the value is found, the
containsValue
containsValue function returns
true
true, otherwise it returns
false
false.

We use the

containsValue
containsValue function to check if "Green" is present in the
Color
Color enum. The first call to
containsValue
containsValue returns
true
true because
Green
Green is a valid enum value. The second call to
containsValue
containsValue returns
false
false because "Yellow" is not a valid enum value.

Common Patterns for Enum Value Existence Checking

When checking if a value exists in an enum, there are several common patterns and techniques that can be used.

One common pattern is to use a conditional statement with the

in
in operator to check if a value exists as a key in the enum object.

Here is an example of using the

in
in operator to check if a value exists in an enum:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
enum Color {
Red,
Green,
Blue,
}
function hasValue(value: any, enumObject: any): boolean {
return value in enumObject;
}
let has: boolean = hasValue("Green", Color);
console.log(has); // Output: true
has = hasValue("Yellow", Color);
console.log(has); // Output: false
enum Color { Red, Green, Blue, } function hasValue(value: any, enumObject: any): boolean { return value in enumObject; } let has: boolean = hasValue("Green", Color); console.log(has); // Output: true has = hasValue("Yellow", Color); console.log(has); // Output: false
enum Color {
Red,
Green,
Blue,
}

function hasValue(value: any, enumObject: any): boolean {
return value in enumObject;
}

let has: boolean = hasValue("Green", Color);
console.log(has); // Output: true

has = hasValue("Yellow", Color);
console.log(has); // Output: false

In this example, we define an enum called

Color
Color with three values:
Red
Red,
Green
Green, and
Blue
Blue. We then create a helper function
hasValue
hasValue that takes a value and an enum object as arguments. The function uses the
in
in operator to check if the given value exists as a key in the enum object. If the value exists, the
in
in operator returns
true
true, otherwise it returns
false
false.

We use the

hasValue
hasValue function to check if "Green" exists in the
Color
Color enum. The first call to
hasValue
hasValue returns
true
true because
Green
Green is a valid enum value. The second call to
hasValue
hasValue returns
false
false because "Yellow" is not a valid enum value.

Creating Custom Functions for Enum Value Validation

In addition to the built-in methods and libraries, you can also create custom functions for enum value validation in TypeScript. These functions can provide specific validation logic tailored to your needs.

Here is an example of creating a custom function for enum value validation:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
enum Color {
Red,
Green,
Blue,
}
function isValidColor(value: any): boolean {
return Object.values(Color).includes(value);
}
let isValid: boolean = isValidColor("Green");
console.log(isValid); // Output: true
isValid = isValidColor("Yellow");
console.log(isValid); // Output: false
enum Color { Red, Green, Blue, } function isValidColor(value: any): boolean { return Object.values(Color).includes(value); } let isValid: boolean = isValidColor("Green"); console.log(isValid); // Output: true isValid = isValidColor("Yellow"); console.log(isValid); // Output: false
enum Color {
Red,
Green,
Blue,
}

function isValidColor(value: any): boolean {
return Object.values(Color).includes(value);
}

let isValid: boolean = isValidColor("Green");
console.log(isValid); // Output: true

isValid = isValidColor("Yellow");
console.log(isValid); // Output: false

In this example, we define an enum called

Color
Color with three values:
Red
Red,
Green
Green, and
Blue
Blue. We then create a custom function
isValidColor
isValidColor that takes a value as an argument. The function uses the
Object.values
Object.values method to get an array of the enum values and then uses the
includes
includes method to check if the given value is included in the array. If the value is found, the function returns
true
true, otherwise it returns
false
false.

We use the

isValidColor
isValidColor function to validate the value "Green". The first call to
isValidColor
isValidColor returns
true
true because
Green
Green is a valid enum value. The second call to
isValidColor
isValidColor returns
false
false because "Yellow" is not a valid enum value.

External Sources

- TypeScript Documentation on Enums: https://www.typescriptlang.org/docs/handbook/enums.html

- enum-utils Library: https://www.npmjs.com/package/enum-utils

How to Implement and Use Generics in Typescript

Generics in TypeScript provide a powerful way to write reusable and type-safe code. This tutorial will guide you through the syntax, concepts, and pr… read more

Tutorial on Gitignore in Typescript

Learn to use gitignore in your Typescript project with this tutorial. Understand the importance of gitignore in TypeScript projects and discover comm… read more

Fixing 'TypeScript Does Not Exist on Type Never' Errors

TypeScript does not exist on type never errors can be frustrating and confusing when encountered in your codebase. However, with the right knowledge … read more

How to Get an Object Value by Dynamic Keys in TypeScript

Retrieving object values by dynamic keys in TypeScript is essential for flexible and dynamic programming. This article provides a step-by-step guide … read more

Tutorial: Readonly vs Const in TypeScript

A detailed comparison of Readonly and Const in TypeScript. This article explores the Readonly and Const keywords in TypeScript, highlighting their di… read more

Tutorial: Working with Datetime Type in TypeScript

Handling and manipulating the Datetime type in TypeScript can be a complex task. In this tutorial, you will learn all about the various aspects of wo… read more

How to Configure the Awesome TypeScript Loader

Learn how to use the Awesome TypeScript Loader to enhance your TypeScript projects. This tutorial will cover topics such as the difference between Ty… read more

How to Run Typescript Ts-Node in Databases

Running Typescript Ts-Node in databases can be a powerful tool for handling data in your applications. This tutorial provides a comprehensive guide o… read more

How to Implement ETL Processes with TypeScript

This article provides a comprehensive guide on creating ETL processes using TypeScript. It covers the purpose of TypeScript in ETL, the benefits of u… read more

Tutorial: Generating GUID in TypeScript

Generating GUIDs in TypeScript can be a task with the right approach. This article provides a concise guide on different methods to generate GUIDs in… read more