How to use a generic function In Typescript
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.
enum GFG {
name = "w3wiki",
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("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
Contact Us