How to Convert a String to an Enum in TypeScript: Complete Tutorial

Online Python Trainer for Beginners

Learn Python easily without overwhelming theory. Solve practical tasks with automatic checking, get hints in Russian, and write code directly in your browser — no installation required.

Start Course

How to Convert a String to an Enum in TypeScript: Step-by-Step Guide

\n\n

Have you ever encountered a situation where an API returns a string, but your TypeScript model is strictly typed using an enum? Or maybe you're getting a value from localStorage and want to safely convert it to an enumeration? If so, you've come to the right place. In this article, we'll break down how to convert a string to an enum in TypeScript — from simple solutions to advanced techniques with error handling.

\n\n

This topic is one of the most popular on Stack Overflow (thousands of views!), and for good reason. Even experienced developers often get confused when it comes to safely converting strings to enumerations. Let's break it all down.

\n\n

What is an enum in TypeScript and why convert it?

\n\n

An enum (enumeration) is a powerful TypeScript tool that allows you to define a set of named constants. Instead of using "magic strings" like 'active' or 'pending', you define an enum and work with typed values. But here's the catch: data from external sources (APIs, forms, configuration files) often comes as plain strings. And that raises the question: how to convert a string to an enum in TypeScript safely and elegantly?

\n\n
// Example enum\nenum Status {\n  Active = 'active',\n  Inactive = 'inactive',\n  Pending = 'pending'\n}\n\n// String from API\nconst apiStatus: string = 'active';\n// How to get Status.Active? 🤔
\n\n

Method 1: Direct Type Assertion

\n\n

The simplest, but also the most dangerous method. You simply tell TypeScript: "Trust me, this is the correct value."

\n\n
const status = apiStatus as Status;\n// or\nconst status = <Status>apiStatus;
\n\n

Pro: Minimal code. Con: If the string doesn't match any enum value, you'll get undefined without warning. TypeScript won't throw an error, and you'll only find out about the problem at runtime when something breaks.

\n\n

This method should only be used if you are absolutely certain about the data source. Not recommended for production.

\n\n

Method 2: Using a Custom Utility Function

\n\n

This is the sweet spot between simplicity and safety. Let's write a function that takes a string and checks if such a value exists in the enum.

\n\n
function stringToEnum<T>(value: string, enumObject: T): T[keyof T] | undefined {\n  // Check if the value exists in the enum\n  const enumValues = Object.values(enumObject) as string[];\n  if (enumValues.includes(value)) {\n    return value as unknown as T[keyof T];\n  }\n  return undefined;\n}\n\n// Usage\nconst status = stringToEnum(apiStatus, Status);\nif (status) {\n  console.log(status); // Status.Active\n} else {\n  console.error('Invalid status value');\n}
\n\n

This function safely converts a string to a TypeScript enum. If the value is not found, it returns undefined, and you can handle that case. Note the generic <T> — it makes the function universal for any enum.

\n\n

Method 3: Strict Approach with Throwing an Error

\n\n

Sometimes undefined is not what you need. It's better to explicitly throw an error to quickly detect the problem.

\n\n
function stringToEnumStrict<T>(value: string, enumObject: T): T[keyof T] {\n  const enumValues = Object.values(enumObject) as string[];\n  if (enumValues.includes(value)) {\n    return value as unknown as T[keyof T];\n  }\n  throw new Error(`Value "${value}" not found in enum`);\n}\n\n// Usage\ntry {\n  const status = stringToEnumStrict(apiStatus, Status);\n  // Work with status\n} catch (error) {\n  console.error(error.message);\n  // Log the error to Sentry or another monitoring system\n}

                
                

Blogs

Book Recommendations