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:

enum Color {
Red,
Green,
Blue,
}

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

Enums can also have string values assigned explicitly:

enum Color {
Red = "RED",
Green = "GREEN",
Blue = "BLUE",
}

Now, Red is assigned the string value "RED", Green is assigned "GREEN", and 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 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:

enum Direction {
North,
East,
South,
West,
}

In this example, we define an enum type called Direction with four values: North, East, South, and 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:

enum Direction {
North = 1,
East = 2,
South = 3,
West = 4,
}

In this example, North is assigned the numeric value 1, East is assigned 2, South is assigned 3, and 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:

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 with three values: Red, Green, and Blue. We then create a variable color and assign it the value Color.Red. When we log color to the console, it displays the numeric value 0, which corresponds to Red.

We can also access the enum values using their numeric values. In the second part of the example, we create a variable colorName and assign it the value Color[1]. When we log 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:

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 with three values: Red, Green, and Blue. We then create a helper function 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, otherwise it returns false.

We use the isValueInEnum function to check if the value 1 exists in the Color enum. The first call to isValueInEnum returns true because Green has the numeric value 1. The second call to isValueInEnum returns false because there is no enum value with the numeric value 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 statement or a series of if statements to compare the value with each enum value.

Here is an example of using a switch statement to check if a value exists in an enum:

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

We use the isValueInEnum function to check if the value 1 exists in the Color enum. The first call to isValueInEnum returns true because Green has the numeric value 1. The second call to isValueInEnum returns false because there is no enum value with the numeric value 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:

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 with three values: Red, Green, and Blue. Each value is assigned a string value. We then create a helper function 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.

We use the findValueByKey function to perform a lookup of the value for the key "Green" in the 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.

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 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 method:

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 with three values: Red, Green, and Blue. We then create a helper function isValidEnumValue that takes a value and an enum object as arguments. The function uses the Object.keys method to get an array of the enum object's keys. It then uses the 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, otherwise it returns false.

We use the isValidEnumValue function to validate the value "Green" in the Color enum. The first call to isValidEnumValue returns true because Green is a valid enum value. The second call to isValidEnumValue returns 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.keys, and Object.entries.

Here is an example of using the Object.values method to validate enum values:

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

We use the includes method to validate the value "Green" in the Color enum. The first call to includes returns true because Green is a valid enum value. The second call to includes returns 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, which provides utility functions for working with enums, including value checking.

Here is an example of using the enum-utils library for enum value checking:

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

We use the containsValue function to check if "Green" is present in the Color enum. The first call to containsValue returns true because Green is a valid enum value. The second call to containsValue returns 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 operator to check if a value exists as a key in the enum object.

Here is an example of using the in operator to check if a value exists in an enum:

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

We use the hasValue function to check if "Green" exists in the Color enum. The first call to hasValue returns true because Green is a valid enum value. The second call to hasValue returns 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:

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

We use the isValidColor function to validate the value "Green". The first call to isValidColor returns true because Green is a valid enum value. The second call to isValidColor returns 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