Typescript Convert String/Number to Enum example
- Admin
- Feb 24, 2024
- Typescript Angular
The enum contains both string and number properties. Converting from a string or number to an enum isn’t automatic and lacks a built-in method. This post discusses parsing strings or numbers to and from an enum, providing examples.
You can check my other posts on typescript Enum object
- enum size in typescript
- Convert Enum to Array
- Check String or Integer exists in Enum
- Compare Enum Strings and Numbers
- 7 ways of Iteration or looping Enum data
- typescript enumeration
Let’s declare the Month enum, which holds properties of strings only. We’ll utilize this enum object throughout this tutorial.
export enum Month {
JAN,
FEB,
MAR,
APR,
MAY,
JUN,
}
console.log(MONTH);
How to Convert String to Enum in TypeScript?
We’ve created a Month enum with strings.
There are multiple ways to convert to Enum object from a string
using
Enum[string]SyntaxTo retrieve an enum object for a given string, use the syntax
Enum[string]. In this case, theMonthenum accepts string values and returns anEnumobject. Sinceenumproperties are strongly typed, this approach thrown an error if--noImplicitAnyis enabled, .// To Enum/number var month: Month = Month["JAN"];using keyof & typeof Another approach, especially when the
--noImplicitAnyconfiguration is enabled, involves retrieving enum string information usingkeyofandtypeof, then casting the string withkeyoftypeof` to return the Enum object.const str = "FEB"; let month1:Month= <keyof typeof Month> str;
convert Number to Enum
Enums without explicitly assigned values are automatically assigned values starting from 0, 1, 2, and so on.
Here’s a convertNumberToEnum() method that accepts a Month object and a number. This method checks if the number corresponds to a valid enum object. If not, it returns undefined. The Month enum also provides mappings and reverse mappings of its values.
If you print an enum object, the following are the values.
// mapping data - names to values
JAN-0
FEB-1
MAR-2
APR-3
MAY-4
JUN-5
// Reverse mapping data - values to names
0-JAN,
1-FEB,
2-MAR,
3-APR,
4-MAY,
5-JUN
At runtime, the Enum object can be retrieved using the following code to parse a number into an enum object in TypeScript.
Here is the code for parse number to enum object in typescript
private convertNumberToEnum(object: Month, x:number): Month{
if (typeof object[x] === 'undefined') {
console.log('Invalid Enum number');
return undefined;
}
return object;
}
console.log(convertNumberToEnum(Month,1))//FEB
Conclusion
In summary, you have learned various approaches to converting a string or a number into an corresponding Enum object.
