How to use type assertion In Typescript
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.
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
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