65.9K
CodeProject is changing. Read more.
Home

Getting Enum Names and Values in Typescript

starIconstarIconstarIconstarIconstarIcon

5.00/5 (4 votes)

Jul 23, 2016

CPOL
viewsIcon

13310

Have you ever wanted to enumerate all the names and values of an enum? Now you can.

Introduction

Have you ever had an enum and wanted to enumerate all the names of an enum? Or all the values of the enum? Or even both?!

Well, I had the same problem and I found the solution and now I'm going to share it with you.

Using the Code

Install the npm package enum-values:

npm install --save enum-values

Using the library is pretty easy (the example is in TypeScript):

import { EnumValues } from 'enum-values';

// Suppose we have an enum
enum SomeEnum {
  VALUE1,
  VALUE2,
  VALUE3
}

// names will be equal to: ['VALUE1', 'VALUE2', 'VALUE3']
var names = EnumValues.getNames(SomeEnum);

// values will be equal to: [0, 1, 2]
var values = EnumValues.getValues(SomeEnum);

// namesAndValues will be equal to:
// [
//  { name: 'VALUE1', value: 0 },
//  { name: 'VALUE2', value: 1 },
//  { name: 'VALUE3', value: 2 }
// ]
var namesAndValues = EnumValues.getNamesAndValues(SomeEnum);