Click here to Skip to main content
15,885,365 members
Articles / Web Development / Node.js
Tip/Trick

Getting Enum Names and Values in Typescript

Rate me:
Please Sign up or sign in to vote.
5.00/5 (4 votes)
23 Jul 2016CPOL 13K   2  
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)


Written By
United States United States
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
-- There are no messages in this forum --