Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / web / Node.js

Getting Enum Names and Values in Typescript

5.00/5 (4 votes)
23 Jul 2016CPOL 13.2K  
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:

PowerShell
npm install --save enum-values

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

JavaScript
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);

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)