How to convert Enum to String and Number in Typescript
- Admin
- Mar 6, 2024
- Typescript Javascript
This post explains how to convert Enums to Strings/Numbers in JavaScript/TypeScript with examples.
TypeScript Enums containing Strings and Numeric Data
Learn how to convert Enum data types to Strings or Numbers in TypeScript.
You can also refer to my previous posts on TypeScript enumeration:
- enum size in typescript
- Convert Enum to Array of Objects
- Check String or Integer exists in Enum
- Compare Enum Strings and Numbers
- 7 ways of Iteration or looping Enum data
- [typescript enumeration](/2018/07/typescript-enumeration-tutorials-best.html
- Convert String to Enum
An Enum, short for Enumeration, is a new syntax that replaces the need for defining multiple constant declarations.
Enum types contain constants of Strings and Numbers only. A String is a group of characters enclosed in double quotes.
Enum is a predefined constant in TypeScript, created using the enum
keyword. Let’s explore several ways of creating Enum types.
Simple Enum example
enum WeekEnd {
Sunday,
Saturday
}
console.log(WeekEnd); // { '0': 'Sunday', '1': 'Saturday', Sunday: 0, Saturday: 1 }
In the example above, the Enum object stores two types of values - one type stores indices and Enum strings, while the other type stores the reverse data like String and Enum.
By default, each Enum constant is assigned numbers starting from 0, 1, i.e., Sunday=0, Saturday=1.
Defined enumeration with initialized string values:
enum WeekEndMap {
Sunday = "Sunday",
Saturday = "Saturday"
}
console.log(WeekEndMap); // { Sunday: 'Sunday', Saturday: 'Saturday' }
console.log(typeof WeekEndMap); // object
Let us see examples Transfering enum values into string numbers in javascript/typescript.
Converting Enum to String in TypeScript
It is a simple conversion to convert to a string.
In the code below, the Enum is supplied with an Enum key and returns strings.
var weekName: string = WeekEnd[WeekEnd.Sunday];
console.log(weekName); // Sunday
console.log(typeof weekName); // string
var weekName: string = WeekEndMap.Saturday;
console.log(weekName); // Saturday
console.log(typeof weekName); // string
Converting Enum to Number in JavaScript/TypeScript
The Enum object stores two pairs of data: keys and values, and their reverse types, where the value is numeric.
To convert this to numeric, the Enum is supplied with Enum key strings and returns numbers.
var weekEndNumber: number = WeekEnd["Saturday"];
console.log(weekEndNumber); // 1
console.log(typeof weekEndNumber); // number
Conclusion
In this example, you learned how to convert Enum types to strings and numbers in TypeScript.