Typescript Example - Convert String/Number to Enum in javascript example


enum contains strings and number properties, Converting from String/number to enum is not automatic and no built in method.

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

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

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"];

Other 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 are assigned with values 0,1,2 onwards.

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

If you print enum object, the following are the values

// mapping data - namesto 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, Enum object can be retrieve 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
Similar Posts