string to enum typescript code example

Example 1: typescript enum to string

enum AnEnum {
    One = 1,
    Two = 2
}
let stringOne = AnEnum[1]; // "One"
let stringTwo = AnEnum[AnEnum.Two]; // "Two"

Example 2: ts enum definition

enum PrintMedia {
  Newspaper,
  Newsletter,
  Magazine,
  Book
}

Example 3: typescript string to enum

enum Day {
    BeforeNoon = "AM",
    AfterNoon = "PM"
} 

var beforeNoon : string = "AM";
var enumValue : Day = (<any>Day)[beforeNoon];

Example 4: enum in ts

enum Direction {
    Up,
    Down,
    Left,
    Right,
}

Example 5: typescript enum value to enum

enum Number {
  One,
  Two
}  

const numberOne: Number = "One" as Number;
const otherNumberOne: Number = Number.One;

const stringOne = Number[Number.One];