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
How to Convert String to Date in TypeScript ?
In TypeScript, conversion from string to date can be done using the Date object and its method. We can use various inbuilt methods of Date object like new Date() constructor, Date.parse(), and Date.UTC.Table of ContentUsing new Date()Using Date.parse() Using Date.UTC()Using new Date()In this approac
2 min read
How to Convert String to Boolean in TypeScript ?
In Typescript, sometimes you receive the data as strings but need to work with boolean values or identify the boolean equivalent of it.There are several approaches to convert string to boolean in TypeScript which are as follows:Table of ContentUsing Conditional StatementUsing JSON.parse() MethodUsin
4 min read
How to Convert String to JSON in TypeScript ?
Converting a string to JSON is essential for working with data received from APIs, storing complex data structures, and serializing objects for transmission. Below are the approaches to converting string to JSON in TypeScript:Table of ContentConvert String to JSON Using JSON.parse()Convert String to
5 min read
How to Convert String to Number in TypeScript?
In TypeScript, converting a string to a number is a common operation that can be accomplished using several different methods. Each method offers unique advantages and can be chosen based on the specific requirements of your application. Below are the approaches to convert string to number in TypeSc
4 min read
How to Convert a Bool to String Value in TypeScript ?
When we talk about converting a boolean to a string value in TypeScript, we mean changing the data type of a variable from a boolean (true or false) to a string (a sequence of characters). We have multiple approaches to convert a bool to a string value in TypeScript.Example: let's say you have a var
3 min read
How to Convert Typescript Dictionary to String ?
In TypeScript, dictionaries are often represented as the objects where keys are associated with the specific values. Converting a TypeScript dictionary to a string is an important task when doing API calls where we cast the JSON response from the API to a string. Below are the ways to convert a Type
4 min read
How to Convert an Object to a JSON String in Typescript ?
In TypeScript, an object is a collection of related data and functionality. Objects are made up of properties and methods. Properties describe the object, methods describe what it can do.Table of ContentUsing JSON.stringify()Using json-stringify-safe libraryUsing a Custom Serialization FunctionUsing
5 min read
How to Convert Map to JSON in TypeScript ?
In TypeScript, we can convert the Map to JSON by manipulating the key-value pairs of the Map into JSON-formatted string. We can use various approaches like JSON.stringify, fast-json-stringify, and json-stringify-safe Libraries for the conversion.Table of ContentUsing JSON.stringifyUsing fast-json-st
5 min read
How to Convert a Set to an Array in TypeScript ?
A Set in TypeScript is used to create a particular type of list that does not contain duplicate elements. If any element is repeated more than once it will automatically remove the duplicate existence and consider it only once in the list. In this article, we will convert these types of lists into a
5 min read
How to Format Strings in TypeScript ?
Formatting strings in TypeScript involves combining and structuring text to produce clear and readable output. This practice is essential for creating dynamic and user-friendly applications, as it allows developers to seamlessly integrate variables and expressions into strings, enhancing the overall
3 min read