. Advertisement .
..3..
. Advertisement .
..4..
Several of us, may continue to encounter numerous issues when using your software. We may wonder “How to Convert a String to Enum in TypeScript” when we try to write data. It is one of the most frequently asked questions by programmers. So, what can we handle this problem? We’ll collaborate to find a better solution. Let’s read this article.
How to Convert a String to Enum in TypeScript?
Solution 1: Utilize the keyword enum
The word “enum” is used to define an enum because its name implies that it is for numeric values only. Look at following example:
enum enumBasic {
x = 5,
y = 9,
z = 7,
}
console.log(enumBasic);
Output
{
"5": "x",
"9": "y",
"7": "z",
"x": 5,
"y": 9,
"z": 7
}
Solution 2: Do as the following guide
To convert a string to enum in Typescript, let’s do as the following guide:
- Give the Enum object the provided string to use as a key.
- The value will be returned if the string is a component of the enum name entry.
- Then cast it to an enum object to obtain a string of the desired enum type.
Let’s follow this example to understand more:
We have an enum object of type Day that is created and represents the method returnDayOfTime ().
enum Day { BeforeNoon = "AM", AfterNoon = "PM" }
function returnDayOfTime(day : Day){ console.log(day); }
A string variable in our code has the value BeforeNoon.
var beforeNoon : string = "BeforeNoon";
By passing the aforementioned string to the enum object, we can obtain the enum value. (we are passing Actual Value here).
var enumValue = Day["BeforeNoon"];
The string key will give “Property does not exist on type” error in the case it does not exists in enum object.
var enumValue = Day["BeforeNoon1"];
Property 'BeforeNoon1' does not exist on type 'typeof Day'. Did you mean 'BeforeNoon'
What happens if we pass a variable rather than a real string?
var enumValue = Day[beforeNoon];
Element implicitly has an ‘any’ type because expression of type ‘string’ can’t be used to index type ‘typeof Day’.
We must cast it to an enum object as shown below to prevent this problem.
var enumValue = (Day)[beforeNoon];
or
var enumValue : Day = (Day)[beforeNoon];
Now that we have transformed the enum to a string, we can provide it to the method returnDayOfTime, which takes an enum object as an argument.
returnDayOfTime(enumValue);
//AM
EnumValue will be undefined if the string is not included in the entry for the enum name.
var enumString = "day";
var enumValue : Day = (Day)[enumString]; //undefined
Solution 3: Utilize keyof typeof
Another solution for you to convert a string to enum in Typescript is utilizing keyof typeof. Thanks to this, you can obtain a type that represents all Enum keys as strings.
enum EmailStatus {
Read,
Unread,
Draft,
}
// type T = "Read" | "Unread" | "Draft" type T = keyof typeof EmailStatus;
If there is a mismatch, you will receive an error if you set the string type to one of the enum’s potential types.
enum EmailStatus {
Read,
Unread,
Draft,
}
// Error: Type "Test" is not assignable to type "Read" | "Unread" | "Draft" const
str2: keyof typeof EmailStatus = 'Test';
console.log(EmailStatus[str2]); // undefined
You may access the enum value that represents the given string by utilizing bracket notation as following:
enum EmailStatus {
Read,
Unread,
Draft,
}
const str2: keyof typeof EmailStatus = 'Read';
console.log(EmailStatus[str2]); //0
What is Enum in TypeScript?
Enum is one of the attributes TypeScript that isn’t a type-level extension of JavaScript.
A developer can define a set of named constants by using enums. Enums can be used to generate a set of unique scenarios or to make it simpler to document purpose. Both numeric and string-based enums are offered by TypeScript.
Why Enums? Enums are helpful in TypeScript for the following reasons:
- Thanks to enumms, future value changes will be simple.
- It lessens mistakes brought on by mistyping or moving a number.
- It does not allocate memory because it only exists at compile time.
- With JavaScript’s inline code, runtime and compilation time are both reduced.
- It enables us to develop simple constants to connect to the program.
- JavaScript does not have enums, but TypeScript enables us to access them, allowing developers to create memory-efficient custom constants in that language.
- In TypeScript, there are three different sorts of enums. They are: String Enums, Numeric Enums, Heterogeneous Enums.
Conclusion
The solutions presented are simple methods to the aforementioned major issue “How to Convert a String to Enum in TypeScript“. We believe that you can easily resolve your probelm with these solutions. You can leave your suggestions and ideas in the comments section if you have any further concerns. Thank you for reading!
Read more
Leave a comment