How to Convert a String to enum in TypeScript?
Last Updated :
08 Aug, 2024
In TypeScript, an enum is a type of class that is mainly used to store the constant variables with numerical and string-type values. In this article, we will learn, how we can convert a string into an enum using TypeScript.
These are the two approaches that can be used to solve it:
Using custom mapping
In this approach, we will define an enum initialized with string values and then map through each item to compare them with a string and return the matching enum value to convert the string into an enum.
Example: The below example will explain how you can convert a string into an enum using custom mapping.
JavaScript
enum GFG {
name = "GeeksforGeeks",
desc = "A Computer Science portal."
}
// Function to convert string into enum
function convertStrToEnum(convertingStr: string):
GFG | string {
switch (convertingStr) {
case "GeeksforGeeks":
return GFG.name;
case "A Computer Science portal.":
return GFG.desc;
default:
return `Pass either "${GFG.name}" or "${GFG.desc}"
as testing string to the function`;
}
}
console.log(convertStrToEnum("GeeksforGeeks"));
console.log(convertStrToEnum("TypeScript"));
console.log(convertStrToEnum("A Computer Science portal."));
Output:
GeeksforGeeks
Pass either "GeeksforGeeks" or "A Computer Science portal." as testing string to the function
A Computer Science portal.
Using the keyof and typeof operators together
The keyof and the typeof operators can together be used to convert an string into an enum in TypeScript.
Syntax:
const variable_name: keyof typeof enum_name = value;
Example: The below example will explain the use of the keyof and typeof operators to convert a string into an enum.
JavaScript
enum GFG {
name = 25,
desc = 56
}
// Converting string to enum
const myStr: keyof typeof GFG = 'name';
const myStr1: keyof typeof GFG = 'desc';
// It prints 25, as the string is now converted
// to the value of first constant of enum
console.log(GFG[myStr]);
// It prints 56, as the string is now converted
// to the value of second constant of enum
console.log(GFG[myStr1]);
Output:
25
56
Using type assertion
In this method, we will convert a string to an enum by using the unknown type assertion at the time of conversion.
Syntax:
const variable_name1: string = value_as_enum_key_as_string;
const variable_name2 = variable_name1 as unknown as enum_name;
Example: The below code example illustrate the type assertion approach to convert a string into enum using TypeScript.
JavaScript
enum GFG {
num1 = 28,
num2 = 56,
num3 = 84
}
// Assigning enum values to
// string type variables
const str1: string = 'num1';
const str2: string = 'num2';
const str3: string = 'num3';
// Converting String into enum
const str1ToEnum = str1 as unknown as GFG;
const str2ToEnum = str2 as unknown as GFG;
const str3ToEnum = str3 as unknown as GFG;
console.log(GFG[str1ToEnum]);
console.log(GFG[str2ToEnum]);
console.log(GFG[str3ToEnum]);
Output:
28
56
84
Using a generic function
In this approach, we'll create a generic function that ensures type safety during the conversion of a string to an enum. The function checks if the provided string matches any of the enum values and returns the corresponding enum value or a message indicating the valid options.
Syntax:
function convertStrToEnum<T extends keyof typeof enum_name>(convertingStr: string): enum_name |
string {
// Implementation
}
Example: The following example demonstrates the usage of a generic function approach to convert a string into an enum.
JavaScript
enum GFG {
name = "GeeksforGeeks",
desc = "A Computer Science portal."
}
// Generic function to convert string into enum
function convertStrToEnum<T extends keyof typeof GFG>(convertingStr: string): GFG
| string {
if (Object.values(GFG).includes(convertingStr as GFG)) {
return convertingStr as GFG;
} else {
return `Pass either "${GFG.name}" or
"${GFG.desc}" as testing string to the function`;
}
}
console.log(convertStrToEnum("GeeksforGeeks"));
console.log(convertStrToEnum("TypeScript"));
console.log(convertStrToEnum("A Computer Science portal."));
Output:
GeeksforGeeks
Pass either "GeeksforGeeks" or "A Computer Science portal." as testing string to the function
A Computer Science portal.
Using Reverse Mapping
In this approach, we use the reverse mapping feature of TypeScript enums to convert a string to an enum. This method leverages the fact that enums in TypeScript generate both forward and reverse mappings.
Example: The following example demonstrates how to use reverse mapping to convert a string into an enum in TypeScript.
JavaScript
enum ExampleEnum {
FIRST = "FirstValue",
SECOND = "SecondValue",
THIRD = "ThirdValue"
}
function convertStringToEnum(value: string): ExampleEnum | undefined {
return (Object.values(ExampleEnum) as Array<string>).includes(value) ? (value as ExampleEnum) : undefined;
}
const testString1 = "FirstValue";
const testString2 = "FourthValue";
console.log(convertStringToEnum(testString1));
console.log(convertStringToEnum(testString2));
Output:
FirstValue
undefined
Using a Lookup Object
In this approach, we create a lookup object that maps string values to their corresponding enum values. This method provides an efficient and straightforward way to convert a string into an enum by directly accessing the lookup object.
Example: The below example demonstrates how to convert a string into an enum using a lookup object.
JavaScript
enum ExampleEnum {
FirstValue = "Nikunj",
SecondValue = "Dhruv",
ThirdValue = "Yash",
}
const enumLookup: { [key: string]: ExampleEnum } = {
FirstValue: ExampleEnum.FirstValue,
SecondValue: ExampleEnum.SecondValue,
ThirdValue: ExampleEnum.ThirdValue,
};
function convertStringToEnum(value: string): ExampleEnum | undefined {
return enumLookup[value];
}
console.log(convertStringToEnum("FirstValue"));
console.log(convertStringToEnum("SecondValue"));
console.log(convertStringToEnum("UnknownValue"));
OutputNikunj
Dhruv
undefined
Similar Reads
TypeScript Tutorial TypeScript is a superset of JavaScript that adds extra features like static typing, interfaces, enums, and more. Essentially, TypeScript is JavaScript with additional syntax for defining types, making it a powerful tool for building scalable and maintainable applications.Static typing allows you to
8 min read
Difference between TypeScript and JavaScript Ever wondered about the difference between JavaScript and TypeScript? If you're into web development, knowing these two languages is super important. They might seem alike, but they're actually pretty different and can affect how you code and build stuff online.In this article, we'll break down the
4 min read
TypeScript Interview Questions and Answers TypeScript, a robust, statically typed superset of JavaScript, has become a go-to language for building scalable and maintainable applications. Developed by Microsoft, it enhances JavaScript by adding static typing and modern ECMAScript features, enabling developers to catch errors early and improve
15+ min read
TypeScript Map TypeScript Map is a collection that stores key-value pairs, where keys and values can be of any type. It maintains the insertion order of keys and provides methods to add, retrieve, check, remove, and clear entries, ensuring efficient management of key-value data.Creating a MapA map can be created a
3 min read
Typescript Set A Set in TypeScript is a bunch of unique values. It is part of the ECMAScript 2015 (ES6) standard and is implemented as a native object in JavaScript.Unlike arrays, sets do not allow duplicate elements, making them useful for storing collections of unique items. TypeScript provides strong typing for
3 min read
TypeScript Array map() Method The Array.map() is an inbuilt TypeScript function that creates a new array with the results of calling a provided function on every element in the array.Syntax:array.map(callback[, thisObject])Parameters: This method accepts two parameters as mentioned above and described below: callback: This param
2 min read
Introduction to TypeScript TypeScript is a syntactic superset of JavaScript that adds optional static typing, making it easier to write and maintain large-scale applications.Allows developers to catch errors during development rather than at runtime, improving code reliability.Enhances code readability and maintainability wit
5 min read
How to Format Date in TypeScript ? Formatting dates is important especially when displaying them to the users or working with date-related data. TypeScript provides various ways to achieve this. Below are the methods to format the date data type in TypeScript:Table of ContentUsing toLocaleString() methodUsing toLocaleDateString() met
3 min read
Data types in TypeScript In TypeScript, a data type defines the kind of values a variable can hold, ensuring type safety and enhancing code clarity.Primitive Types: Basic types like number, string, boolean, null, undefined, and symbol.Object Types: Complex structures including arrays, classes, interfaces, and functions.Prim
3 min read
How do I Remove an Array Item in TypeScript? In this article, we will learn about the different ways of removing an item from an array in TypeScript. In TypeScript, an array can be defined using union typing if it contains items of different types. We can use the following methods to remove items from a TypeScript array:Table of ContentUsing t
4 min read