How to convert Enum to String/Number in  javascript/typescript


This post covers how to convert Enum to String/Number in javascript/typescript with an example.

Typescript Enum contains strings and numeric data

In this post, We are going to discuss How to Convert Enum data type to String or numbers in typescript

You can also check my previous post typescript enumeration

Enum is called Enumeration, It is a new syntax for replacing define multiple constants declaration, Enum type contains constants of Strings and numbers only. The string is a group of characters enclosed in double-quotes.

Enum are predefined constants, can be created using the enum keyword. In typescript, String can be created as follows. Let’s see several ways of creating enums type Simple Enum example

enum WeekEnd {
Sunday,
Saturday
}
console.log(WeekEnd); // { '0': 'sunday', '1': 'saturday', sunday: 0, saturday: 1 }

As you see enum object is used to store two types of values - one type stores index and  enum strings, other type stores reverse of data like string and enum.

By default, each enum constants is assigned with numbers starting from 0,1 ie. Sunday=0, Saturday=1

defined enumeration with initializing 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

How to convert Enum to String in javascript

This is a simple conversion convert to string.

In the below code, Enum supplied with 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); // object

how to Convert Enum to Number in javascript/typescript

Enum object stores two pairs of data ie key and value and reverse of its types and value is numeric, To convert this to numeric, Enum supplied with enum key strings and returns numbers.

var weekEndNumber: number = WeekEnd['saturday'];
console.log(weekEndNumber); // 1
console.log(typeof weekEndNumber); // Number
Similar Posts