How to Check if a Value Exists in an Enum in TypeScript?

While building an e-commerce application in TypeScript, you might define a ProductCategory enum for valid categories like ‘electronics’, ‘clothing’, and ‘food’. When receiving data from a user or an API, it’s important to check if the provided category actually exists in the enum.

This prevents invalid values from being processed or stored. This ensures your application handles only valid, expected data and avoids potential bugs.

In this tutorial, I will explain how to check if a value exists in an Enum in TypeScript. Enums allow developers to define a set of named constants, making it easier to document intent and create distinct cases.

Enums are a powerful feature in TypeScript that can help improve code readability and maintainability. We’ll explore different methods to determine if a specific value is part of an enum and provide real-world examples to illustrate the concepts.

Understand Enums in TypeScript

Before diving into checking if a value exists in an enum, let’s briefly review what enums are in TypeScript. An enum is a way to define a set of named constants. Each constant in the enum is assigned a numeric value, starting from 0 by default.

Here’s an example of a simple enum representing different states in the United States:

enum USState {
  California,
  Texas,
  Florida,
  NewYork,
  Illinois
}

Check out: Convert TypeScript Enum to String

Check if a Value Exists in an Enum in TypeScript

Now, let’s explore different ways to check if a value exists in an enum in TypeScript.

Method 1: Using the in Operator in TypeScript

One straightforward approach to check if a value exists in an enum is by using the in operator. The in operator checks if a property exists in an object or its prototype chain. You can use the in operator to check if a value is a property of the enum object.

Here’s an example:

enum USState {
  California,
  Texas,
  Florida,
  NewYork,
  Illinois
}

const state = 'California';

if (state in USState) {
  console.log(`${state} is a valid US state.`);
} else {
  console.log(`${state} is not a valid US state.`);
}

In this code, we define the USState enum and then check if the state variable exists as a property in the USState enum using the in operator. If the value exists, it means it is a valid enum value.

Check if a Value Exists in an Enum in TypeScript

Check out: Convert TypeScript Enums to Arrays

Method 2: Using the Enum Object in TypeScript

Another approach to check if a value exists in an enum is by directly accessing the enum object. Enums in TypeScript are essentially objects, so you can use bracket notation or dot notation to access the enum values.

Here’s an example using bracket notation:

enum USState {
  California,
  Texas,
  Florida,
  NewYork,
  Illinois
}

const state = 'Texas';

if (USState[state] !== undefined) {
  console.log(`${state} is a valid US state.`);
} else {
  console.log(`${state} is not a valid US state.`);
}

This code uses bracket notation USState[state] to access the enum value. If the value exists in the enum, it will return the corresponding numeric value.

If the value doesn’t exist, it will return undefined. We can check for its presence by comparing it with undefined.

Check enum exist value using Enum Object in TypeScript

Method 3: Using the hasOwnProperty Method in TypeScript

Another way to check if a value exists in an enum is by using the hasOwnProperty method. This method is available on all JavaScript objects and returns a boolean indicating whether the object has the specified property as its own property.

Here’s an example:

enum USState {
  California,
  Texas,
  Florida,
  NewYork,
  Illinois
}

const state = 'Florida';

if (USState.hasOwnProperty(state)) {
  console.log(`${state} is a valid US state.`);
} else {
  console.log(`${state} is not a valid US state.`);
}

In this code, we use the hasOwnProperty method on the USState enum object to check if the state value exists as a property. If it does, it will return true, indicating that it is a valid enum value.

Check if Value Exists in Enum Using the hasOwnProperty in TypeScript

Check out: Check String in Enum TypeScript

Real-World Example in TypeScript

Let’s consider a real-world scenario where checking if a value exists in an enum can be useful. Imagine you are building an e-commerce application that allows users to select their shipping state. You want to ensure that the user selects a valid US state from a predefined list.

Here’s an example of how you can use enums and check if the selected state is valid:

// Define the enum
enum USState {
  California = 'CA',
  Texas = 'TX',
  Florida = 'FL',
  NewYork = 'NY',
  Illinois = 'IL'
}

// Function to process the order based on state code
function processOrder(stateCode: string) {
  // Find the enum entry that matches the state code
  const stateEntry = Object.entries(USState).find(([_, code]) => code === stateCode);

  if (stateEntry) {
    const [stateName, code] = stateEntry;
    console.log(`Processing order for ${stateName}`);
    // Add your order processing logic here
  } else {
    console.log('Invalid shipping state selected.');
    // Handle invalid state code here
  }
}

// Example usage
processOrder('CA'); // Output: Processing order for California
processOrder('TX'); // Output: Processing order for Texas
processOrder('NY'); // Output: Processing order for NewYork
processOrder('GA'); // Output: Invalid shipping state selected.

This example defines the USState enum with state abbreviations as values. The processOrder function takes the selected state as a parameter and checks if it exists in the USState enum using the in operator.

If the state is valid, it proceeds with the order processing logic. If the state is invalid, it handles the case accordingly.

Check Exist Value in TypeScript

Conclusion

Checking if a value exists in an enum is a common task in TypeScript development. In this tutorial, we explored different methods to achieve this, including using the in operator, accessing the enum object directly, and using the hasOwnProperty method. By understanding these techniques, you can ensure that your code handles enum values correctly and provides a better user experience.

Remember, enums are a powerful feature in TypeScript that can help improve code readability and maintainability. When working with enums, it is important to validate user input and handle cases where invalid values may be provided.

I hope this tutorial has helped you understand how to check if a value exists in an enum in TypeScript. Happy coding!

You may like to read:

51 Python Programs

51 PYTHON PROGRAMS PDF FREE

Download a FREE PDF (112 Pages) Containing 51 Useful Python Programs.

pyython developer roadmap

Aspiring to be a Python developer?

Download a FREE PDF on how to become a Python developer.

Let’s be friends

Be the first to know about sales and special discounts.