How to use custom mapping In Typescript
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.
enum GFG {
name = "w3wiki",
desc = "A Computer Science portal."
}
// Function to convert string into enum
function convertStrToEnum(convertingStr: string):
GFG | string {
switch (convertingStr) {
case "w3wiki":
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("w3wiki"));
console.log(convertStrToEnum("TypeScript"));
console.log(convertStrToEnum("A Computer Science portal."));
Output:
w3wiki
Pass either "w3wiki" or "A Computer Science portal." as testing string to the function
A Computer Science portal.
How to Convert a String to enum in TypeScript?
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:
Table of Content
- Using custom mapping
- Using the keyof and typeof operators together
- Using type assertion
- Using a generic function