{

Typescript Convert String/Number to Enum example


Typescript Comment Types

enum contains strings and number properties, Converting from String/number to enum is not automatic and has no built-in method. This post talks about parsing string/number to/and from enum with examples.

You can check my other posts on typescript Enum object

Let’s declare Month enum constants holds properties of strings only. Let’s use this as an enum object for this tutorial.

export enum Month {
  JAN,
  FEB,
  MAR,
  APR,
  MAY,
  JUN,
}
console.log(MONTH);

How to Convert String to Enum in typescript?

Created Month enum with strings,

In typescript, Enum properties are strongly typed. In the first approach, Month enum accepts strings values and returns Enum object.

This will not work if --noImplicitAny is enabled and throws an error.

// To Enum / number
var month : Month = Month["JAN"];

Another approach when --noImplicitAny configuration is enabled,

We used to get enum string information using keyof and typeof cast string with keyof typeof and return Enum object.

const str = "FEB";
 let  month1:Month= <keyof typeof Month> str;

Parse/convert Number to Enum

Enum without values is assigned with values 0,1,2 onwards.

Following is a convertNumberToEnum() accepts Month object and number This method checks if a number is not an enum object, It returns undefined. Month enum has a mapping and reverses mapping of its values,

If you print 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 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
THE BEST NEWSLETTER ANYWHERE
Join 6,000 subscribers and get a daily digest of full stack tutorials delivered to your inbox directly.No spam ever. Unsubscribe any time.

Similar Posts
Subscribe
You'll get a notification every time a post gets published here.