How to convert Enum to String and Number in Typescript

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

Typescript Enum contains strings and numeric data

Learn, 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 is a predefined constant in typescript. It creates using the enum keyword. Let’s see several ways of creating enums type Simple Enum example

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

Above, enum object stores 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 constant 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 Typescript

It is a simple conversion convert to string.

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

how to Convert Enum to Number in javascript/typescript

Enum object stores two pairs of data i.e key and value and reverse of its types. and value is numeric.

To convert this to numeric, Enum is supplied with enum key strings and returns numbers.

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


In this example, you learned how to convert enum type to string and numbers in Typescript example.